【问题标题】:MongoDB, How Do I combine a find and sort with the $cond in aggregation?MongoDB,如何将查找和排序与聚合中的 $cond 结合起来?
【发布时间】:2020-07-04 11:21:53
【问题描述】:

我写了一个查找查询,它有效,查找查询返回名称和级别存在的记录

db.docs.find( { $and: [{name:{$exists:true}},{level:{ $exists:true}} ] },{_id:0, name:1}).sort({"name":1})

现在想将它与下面的代码结合起来,它也可以工作,但需要与上面的代码合并以提取正确的数据

db.docs.aggregate(
   [
      {
         $project:
           {
             _id:0,
             name: 1,
             Honours:
               {
                 $cond: { if: { $gte: [ "$level", 8 ] }, then: "True", else: "False" }
               }
           }
      }
   ]
)

find 查询返回 name 和 level 存在的记录,但我需要使用名为 Honours 的新列来增强结果,根据 level 是否为 gte(大于或等于 8)显示 True of False

所以我基本上试图将上面的 find 过滤器与 $cond 函数结合起来(我在这里找到并修改了示例:$cond

我尝试了以下和其他一些排列来尝试使用 $project 和 $cond 聚合进行查找和排序,但它返回了错误。我对如何构建 mongodb 语法以使其完全融合在一起非常陌生。有人可以帮忙吗?

db.docs.aggregate(
   [{{ $and: [{name:{$exists:true}},{level:{ $exists:true}} ] },{_id:0, name:1}).sort({"name":1}
      {
         $project:
           {
             _id:0,
             name: 1,
             Honours:
               {
                 $cond: { if: { $gte: [ "$level", 8 ] }, then: "True", else: "False" }
               }
           }
      }
}
   ]
)

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    试试下面的聚合管道:

    db.docs.aggregate([
      /** $match is used to filter docs kind of .find(), lessen the dataset size for further stages */
      {
        $match: {
          $and: [{ name: { $exists: true } }, { level: { $exists: true } }]
        }
      },
      /** $project works as projection - w.r.t. this projection it will lessen the each document size for further stages */
      {
        $project: {
          _id: 0,
          name: 1,
          Honours: {
            $cond: { if: { $gte: ["$level", 8] }, then: "True", else: "False" }
          }
        }
      },
      /** $sort should work as .sort() */
      { $sort: { name: 1 } }
    ]);
    

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 2015-12-28
      • 2016-05-30
      • 1970-01-01
      • 2018-07-15
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多