我有以下mongo查询。
db.ServiceProvider.aggregate([
{
$unwind: "$PostCommentUserIDs"
},
{
$lookup:
{
from: "Parents",
localField: "PostCommentUserIDs",
foreignField: "ID",
as: "ParentDetailsArr"
}
},
{
$match: { "ParentDetailsArr": { $ne: [] } }
}
])
它给出了以下结果:
{
"_id" : ObjectId("57245af1588aec5b118b4567"),
"ServiceProviderID" : 3,
"Title" : "test",
"PostedMessage" : "test",
"TotalComments" : 0,
"TotalShares" : 0,
"TotalThanks" : 0,
"AddedOn" : "2016-04-30",
"LastModifiedOn" : "2016-04-30 07:12:49",
"PostAttachment" : {
"ImagePath" : ""
},
"PostCommentUserIDs" : "3",
"PostComments" : [
{
"ID" : "1462000372388480634",
"UserID" : 3,
"CommentMessage" : "1",
"TotalThanks" : 0,
"AddedOn" : "2016-04-30 07:12:52",
"LastModifiedOn" : "2016-04-30 07:12:52",
"CommentAttachment" : {
"ImagePath" : ""
}
},
],
"Subscriber" : [ ],
"ParentDetailsArr" : [
{
"_id" : ObjectId("572447e6588aec32108b4569"),
"ID" : "3",
"UID" : "0Xb1fHqzR3HZVJWQc8aAbB77UkwSnmasdQrtp9qySVdqipsYs6eC7rEt",
"Name" : "Chinmay Kulkarni",
"ProfileImagePath" : "images3_3_1460348144#SIZE#.jpeg"
}
]
}
{
"_id" : ObjectId("57246137588aec41118b4567"),
"ServiceProviderID" : 3,
"Title" : "test",
"PostedMessage" : "test",
"TotalComments" : 0,
"TotalShares" : 0,
"TotalThanks" : 0,
"AddedOn" : "2016-04-30",
"LastModifiedOn" : "2016-04-30 07:39:35",
"PostAttachment" : {
"ImagePath" : ""
},
"PostCommentUserIDs" : "3",
"PostComments" : [
{
"ID" : "14620019791507102321",
"UserID" : 3,
"CommentMessage" : "1",
"TotalThanks" : 0,
"AddedOn" : "2016-04-30 07:39:39",
"LastModifiedOn" : "2016-04-30 07:39:39",
"CommentAttachment" : {
"ImagePath" : ""
}
},
],
"Subscriber" : [ ],
"ParentDetailsArr" : [
{
"_id" : ObjectId("572447e6588aec32108b4569"),
"ID" : "3",
"UID" : "0Xb1fHqzR3HZVJWQc8aAbB77UkwSnmasdQrtp9qySVdqipsYs6eC7rEt",
"Name" : "Chinmay Kulkarni",
"ProfileImagePath" : "images3_3_1460348144#SIZE#.jpeg"
}
]
}
我想修改上面的查询并为其添加_id条件。所以它只给出了1个与给定_id匹配的结果。
但是无法破解它。请帮忙!
答案 0 :(得分:2)
$match
采用过滤条件。在$ match aggregate function - https://docs.mongodb.org/manual/reference/operator/aggregation/match/
在聚合查询的最后一个管道中运行低于$ match条件的查询。
db.ServiceProvider.aggregate([
{
$unwind: "$PostCommentUserIDs"
},
{
$lookup:
{
from: "Parents",
localField: "PostCommentUserIDs",
foreignField: "ID",
as: "ParentDetailsArr"
}
},
{
$match: { "ParentDetailsArr": { $ne: [] }, "_id" : ObjectId("XXXX") }
}
])