我有商店集合和用户集合,其中包含作为字符串的商店id列表。
车间文件示例:
{
"_id" : ObjectId("5a0c6797fd3eb67969316ce2"),
"picture" : "http://placehold.it/150x150",
"name" : "Genmom",
"email" : "[email protected]",
"city" : "Rabat",
"location" : {
"type" : "Point",
"coordinates" : [
-6.79387,
33.83957
]
}
}
用户集合示例:
{
"_id" : ObjectId("5c04b943ff491824b806686a"),
"email" : "[email protected]",
"password" : "$2a$10$4Wt5Rn6udxREdXCIt3hGb.sKhKUKOlyiYKmLTjYG3SqEPKFSw9phq",
"likedShops" : [
"5a0c6797fd3eb67969316ce2",
"5c07ada8ff49183284e509d1",
"5c07acc1ff49183284e509d0"
],
"dislikedShops" : [ ]
}
我想把喜欢的商店的详细情况告诉你。
最佳答案
您可以使用下面的$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/