【问题标题】:How to get result from aggregate mongoDB?如何从聚合 mongoDB 中获取结果?
【发布时间】:2021-07-01 12:02:52
【问题描述】:

我有如下收藏:

{  "_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 }]} },
])

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

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:
    • $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"
              },
              {}
            ]
          }
        }
      }
    ])
    

    Playground

    【讨论】:

    • 没有按照我的要求工作,如果评论集合 flag.status 将是 truereply.flag.status 将是 false 在那个时候得到重复值。我更新了问题,以便您更好地了解。
    • 实际上你已经在$match中添加了其中一个应该为真的条件,请你解释一下你的$match条件或要求。
    • 我有 comments 集合和 reply 归档数组。如果 userA cmets & userB 对此进行回复。之后,UserC 标记 userA 的评论。此时,userA的数据应该只显示
    • 这种操作在mongodb中是无效事务,建议您根据字段和条件的要求重新设计架构结构。
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2020-07-02
    • 2019-12-29
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多