我有商店集合和用户集合,其中包含商店 ID 列表作为字符串。
商店文件示例:
{
"_id" : ObjectId("5a0c6797fd3eb67969316ce2"),
"picture" : "http://placehold.it/150x150",
"name" : "Genmom",
"email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f232a26232e382e3d2a0f282a21222022612c2022" rel="noreferrer noopener nofollow">[email protected]</a>",
"city" : "Rabat",
"location" : {
"type" : "Point",
"coordinates" : [
-6.79387,
33.83957
]
}
}
用户收集示例:
{
"_id" : ObjectId("5c04b943ff491824b806686a"),
"email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13726a7c66713d787b7a727f53747e727a7f3d707c7e" rel="noreferrer noopener nofollow">[email protected]</a>",
"password" : "$2a$10$4Wt5Rn6udxREdXCIt3hGb.sKhKUKOlyiYKmLTjYG3SqEPKFSw9phq",
"likedShops" : [
"5a0c6797fd3eb67969316ce2",
"5c07ada8ff49183284e509d1",
"5c07acc1ff49183284e509d0"
],
"dislikedShops" : [ ]
}
我想返回 LikeShops 的详细信息。
最佳答案
您可以使用下面的 $lookup
聚合
db.users.aggregate([
{ "$lookup": {
"from": "shops",
"let": { "likedShops": "$likedShops" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$_id", "$$likedShops"] }}}
],
"as": "likedShops"
}}
])
或者,如果您的 ID 是字符串,则使用 $toString
与 ObjectIds
db.users.aggregate([
{ "$lookup": {
"from": "shops",
"let": { "likedShops": "$likedShops" },
"pipeline": [
{ "$match": { "$expr": { "$in": [{ "$toString": "$_id" }, "$$likedShops"] }}}
],
"as": "likedShops"
}}
])
关于database - 在数组中查找 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53636832/