我有文档
{
"_id" : ObjectId("5da832caeb173112348e509b"),
"owner" : {
"image" : "5d999578aeb073247de4bd6e.jpg",
"fullname" : "hem sopheap",
"userID" : "5d999578aeb073247de4bd6e"
},
"project" : {},
"image" : "hem sopheap-1571304138866.png",
"body" : "Lorem Ipsum "),
"comments" : [
{
"user" : "5d999578aeb073247de4bd6e",
"fullname" : "hem sopheap",
"username" : "sopheap",
"comment" : "1000000",
"_id" : ObjectId("5db07900ae100b0c05b1222c"),
"replies" : [],
"date" : ISODate("2019-10-23T15:40:57.535Z"),
"likes" : [
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044"
]
},
{
"user" : "5d999578aeb073247de4bd6e",
"fullname" : "hem sopheap",
"username" : "sopheap",
"comment" : "11111111111",
"_id" : ObjectId("5db0790aae100b0c05b1222d"),
"replies" : [],
"date" : ISODate("2019-10-23T15:40:57.535Z"),
"likes" : []
}
],
"__v" : 33,
"likes" : [
"5d999578aeb073247de4bd6e"
]
}如何获取likes、按帖子_id和评论_id进行过滤以获得结果likes
"likes" : [
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044",
"5da85558886aee13e4e7f044"
]发布于 2019-10-28 00:16:05
让我们将输入简化为这个。我们有两个帖子,P0和P2。每个都有一个数组comments。我们知道comment._id至少在文章中是独一无二的,所以在这里“重用”它们是可以的:
var r =
[
{
"_id" : "P0",
"comments" : [
{ "_id" : "C0", "likes" : [ "AA", "AA" ] }
,{"_id" : "C1", "likes" : [] }
,{"_id" : "C2", "likes" : [ "foo", "bar" ]}
,{"_id" : "C3", "likes" : []
}
]
}
,{
"_id" : "P2",
"comments" : [
{ "_id" : "C0", "likes" : [ "FF", "FF" ] }
,{"_id" : "C1", "likes" : [] }
,{"_id" : "C2", "likes" : [ "foo", "bar" ]}
,{"_id" : "C3", "likes" : []
}
]
}
];这里有一个解决方案:
db.foo.aggregate([
// First, match on post ID and comments ID. Remember, comments is an
// array so ANY comments entry with key C0 inside the array will match and
// yield the entire array. But this is OK because it very much narrows down
// the info to process:
{$match: {_id: "P2", "comments._id":"C0"}}
,{$unwind: "$comments"} // Unwind the comments:
// And now pick only that comment with ID C0:
,{$match: {"comments._id":"C0"}}
// To complete the request, make "likes" a top level field:
,{$project: {"likes": "$comments.likes"}}
]);对OP的完整回答将包括将post和comment _id设置为ObjectId而不是字符串,但查询是相同的。
https://stackoverflow.com/questions/58579776
复制相似问题