首页 > 解决方案 > 如何从聚合 mongoDB 中获取结果?

问题描述

我有一个如下集合:

{  "_id" : ObjectId("5716617f4af77ca97a9614bd"), "flag": { "status": true, "userId": ObjectId"606b0e9f00bece43471baa50")}, "text" : "Main Comment 1", "reply" : [ { "_id" : ObjectId("571661cd4af77ca97a9614c1"), "flag": { "status": true }, "text" : "Main Comment 1 reply 1" }, { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "flag": { "status": true, "userId": ObjectId("606b0e9f00bece43471baa48")}, "text" : "Main Comment 1 reply 2" } ] }

预期结果是,

{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1",  reply: { } }

{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 1" } }

{ "_id" : ObjectId("5716617f4af77ca97a9614bd"), "text" : "Main Comment 1", reply: { "_id" : ObjectId("571661cd4af77ca97a9614c2"), "text" : "Main Comment 1 reply 2" } }

这是我正在使用的查询:

db.comments.aggregate([
{ $unwind: { path: "$reply", preserveNullAndEmptyArrays: true } },
{ $match: { $or: [ { 'flag.status': true }, { 'reply.flag.status': true }]} },
])

通过使用此代码,我没有得到预期的结果。请让我知道该怎么做?

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


  • $match把你的比赛阶段放在第一位
  • $unwind解构reply数组
  • $project显示必填字段并检查条件reply是否flag匹配,reply否则返回空对象
db.comments.aggregate([
  {
    $match: {
      $or: [
        { "flag.status": true },
        { "reply.flag.status": true }
      ]
    }
  },
  {
    $unwind: {
      path: "$reply",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      _id: 1,
      text: 1,
      reply: {
        $cond: [
          { $eq: ["$reply.flag.status", true] },
          {
            _id: "$reply._id",
            text: "$reply.text"
          },
          {}
        ]
      }
    }
  }
])

操场


推荐阅读