【问题标题】:How do I use mongo aggregation to loop through array and return needed documents?如何使用 mongo 聚合循环遍历数组并返回所需的文档?
【发布时间】:2019-07-11 02:59:03
【问题描述】:

我有一个查询,我需要按 ID 查找文档,然后我只需要返回数组内符合特定条件的项目。

在下面的代码中,您将看到我只需要按 ID“匹配”一个文档,然后我将“限制”设置为一个(应该只有一个)。这是我真的很困惑...然后我“展开”作为数组的 fragments 字段,数组内部是子文档。我需要通过其中的数组的最后一项过滤掉这些子文档,因此我“投影”了 assignments_array 的“切片”。这是我只需要assignments_array 为空或assignment_history.to 为空的文档

db.getCollection('territories').aggregate([
    {
      "$match": {
        "congregation": ObjectId("5c68c706f1f52047f08862b3")
      }
    },
    {
      "$limit": 1
    },

    { 
      $unwind: {
        path: "$fragments"
      }
    },
    {
      $project: {
        "fragments.number": 1,
        "fragments.assignment_history": {"$slice": ["$fragments.assignment_history", -1]}
      }
    }

这让我得到这个结果...

{
  "_id": ObjectId("5c68c706f1f52047f08862b6"),
  "fragments": {
    "number": 1,
    "assignment_history": [{
      "to": ObjectId("5c68c706f1f52047f08862b4"),
      "on": 1550370567067
    }]
  }
}
{
  "_id": ObjectId("5c68c706f1f52047f08862b6"),
  "fragments": {
    "number": 2,
    "assignment_history": []
  }
}
{
  "_id": ObjectId("5c68c706f1f52047f08862b6"),
  "fragments": {
    "number": 3,
    "assignment_history": [{
      "to": null,
      "on": 1550370567067
    }]
  }
}

我需要以 2 个对象结束,其中 assignment_history.to 为空,而 assignment_history 没有项目/长度。

【问题讨论】:

  • 你能展示这个地区的一个例子吗?

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

您可以在$unwind 之后再使用一个$match 条件

db.getCollection('territories').aggregate([
  { "$match": { "congregation": ObjectId("5c68c706f1f52047f08862b3") }},
  { "$limit": 1 },
  { "$unwind": { "path": "$fragments" }},
  { "$match": {
    "$or": [
      { "fragments.assignment_history.to": null },
      { "fragments.assignment_history.to": { "$exists": false }}
    ]
  }},
  { "$project": {
    "fragments.number": 1,
    "fragments.assignment_history": { "$slice": ["$fragments.assignment_history", -1] }
  }}
])

【讨论】:

    【解决方案2】:

    尝试在项目之前添加此阶段。 它的意思是给我那些空的fragments.assignment_history, 或者没有fragments.assignment_history.to的人

    {
      $match: {
         $or : [
                { "fragments.assignment_history" : {$size: 0}},
                { 
                  "fragments.assignment_history" :{
                            $not: { $elemMatch: { to : {$exists: true} } 
                  }
                }
               ]
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 1970-01-01
      • 2021-03-25
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 2011-08-21
      相关资源
      最近更新 更多