Javascript 如何使用mongo聚合在数组中循环并返回所需的文档?

Javascript 如何使用mongo聚合在数组中循环并返回所需的文档?,javascript,node.js,mongodb,mongoose,aggregation-framework,Javascript,Node.js,Mongodb,Mongoose,Aggregation Framework,我有一个查询,需要按ID查找文档,然后只需要返回数组中符合特定条件的项 在下面的代码中,您将看到我只需要按ID“匹配”一个文档,然后我将“限制”设置为一个(应该只有一个)。这是我真的感到困惑…我然后“展开”片段字段,它是数组,数组中是子文档。我需要按其中数组的最后一项过滤掉这些子文档,所以我“投影”了数组的“切片”。这是因为我只需要assignments\u数组为空或assignment\u history.to为空的文档 db.getCollection('territories').aggr

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

在下面的代码中,您将看到我只需要按ID“匹配”一个文档,然后我将“限制”设置为一个(应该只有一个)。这是我真的感到困惑…我然后“展开”片段字段,它是数组,数组中是子文档。我需要按其中数组的最后一项过滤掉这些子文档,所以我“投影”了数组的“切片”。这是因为我只需要
assignments\u数组
为空或
assignment\u 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
    }]
  }
}

我需要得到两个对象,其中
assignment\u history.to
为空,而
assignment\u history
没有项目/长度。

您可以在
$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] }
  }}
])

尝试在项目之前添加此阶段。 它的意思是给我那些有空
片段的,
或者那些没有
片段的。分配\u历史。到

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

你能给我举个例子吗?