MongoDB中如何比较同一个文档中的两个字段

我们可以使用聚合表达式$expr.

$expr 允许在查询语言中使用聚合表达式。
$expr 具有以下语法:
{ $expr: { } }
$expr可以构建查询表达式,以比较$match阶段中同一文档中的字段。

查询两个字段相等:
{$expr:{$eq: ["$field1","$field2"]}}
查询比较两个字段:
{$expr:{$gt: ["$field1","$field2"]}}

在C#中Filter的使用比较特殊,不能直接使用像Linq方式的调用
但我们可以构建像上述表达式的文档筛选方式,达到类型效果,具体请参考以下方式:

FilterDefinition<TDocument> filter = new BsonDocumentFilterDefinition<TDocument>(
  new BsonDocument(
    "$expr", new BsonDocument(
      "$eq", new BsonArray
      {
        "$field1", "$field2"
      })));

提示:the $expr operator is supported for the server versions higher or equal to 3.6

posted @   William202020  阅读(1634)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示