当我尝试在mongo db中加入时,$ lookup返回空数组。
我有两个集合,一个是user_information,另一个是add_to_cart。我希望在user_information中使用user_id获取用户表单add_to_cart集合的add_to_cart详细信息。
add_to_cart collection:
[
{
"_id": {
"$id": "592ec12b744a12d014000031"
},
"order_id": "592ec125744a12d014000030",
"table_id": 1,
"category_name": "veg",
"food_id": "5923c8bc744a12441e000031",
"user_id": "592ec125744a12d01400002f",
"food_name": "Cream Of Mushroom Soup",
"food_per_price": "100",
"food_total_price": 100,
"food_qty": 1,
"active_status": 0,
"created_at": {
"sec": 1496236331,
"usec": 0
},
"updated_at": {
"sec": 1496236331,
"usec": 0
}
},
{
"_id": {
"$id": "592ec12e744a12d014000032"
},
"order_id": "592ec125744a12d014000030",
"table_id": 1,
"category_name": "veg",
"food_id": "5923c8cb744a12441e000033",
"user_id": "592ec125744a12d01400002f",
"food_name": "Cream Of Mushroom Soup",
"food_per_price": "100",
"food_total_price": 100,
"food_qty": 1,
"active_status": 0,
"created_at": {
"sec": 1496236334,
"usec": 0
},
"updated_at": {
"sec": 1496236334,
"usec": 0
}
}
]
user_information集合:
[
{
"_id": {
"$id": "592ec125744a12d01400002f"
},
"branch_id": 1,
"brand_id": 1,
"business_id": 1,
"table_id": 1,
"uid": "116907438816775509716",
"user_name": "dhamo dharan",
"user_email": "dhamursv@gmail.com",
"user_provider": "google",
"user_image": "https://lh5.googleusercontent.com/-Masl6FTlG_g/AAAAAAAAAAI/AAAAAAAAAEo/UV3oTjMnqzQ/s96-c/photo.jpg",
"active_status": 0,
"created_at": {
"sec": 1496236325,
"usec": 0
},
"updated_at": {
"sec": 1496236325,
"usec": 0
}
}
]
我的数据库查询
db.add_to_cart.aggregate([
{ "$match": { "user_id": "592ec125744a12d01400002f" } },
{ "$sort": { "created_at": -1 } },
{ "$limit": 20 },
{ "$lookup": {
"from": "user_information",
"localField": "user_id",
"foreignField": "_id",
"as": "userinfo"
} },
{ "$unwind": "$userinfo" },
{ "$project": {
"food_name": 1,
"food_qty": 1,
"userinfo.user_name": 1,
"userinfo.user_email": 1
} }
])
它将返回空的结果我不知道出了什么问题。谢谢提前!
答案 0 :(得分:3)
简单字 - 您的匹配查询错误。
因为“user_id”:“592ec125744a12d01400002f”是一个“字符串”,所以匹配与正常的查询查询一起使用,字符串为ObjectId
但是当我们谈论聚合时,你不能给出直接字符串..你总是给mongoose.Types.ObjectId(userId),其中userId是字符串
var userId="592ec125744a12d01400002f";
db.add_to_cart.aggregate([
{ "$match": { "user_id": mongoose.Types.ObjectId(userId) } },
{ "$sort": { "created_at": -1 } },
{ "$limit": 20 },
{ "$lookup": {
"from": "user_information",
"localField": "user_id",
"foreignField": "_id",
"as": "userinfo"
} },
{ "$unwind": "$userinfo" },
{ "$project": {
"food_name": 1,
"food_qty": 1,
"userinfo.user_name": 1,
"userinfo.user_email": 1
} }
])