【发布时间】: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