【发布时间】:2017-01-09 02:44:01
【问题描述】:
我需要从数据库中检索整个单个对象层次结构作为 JSON。我决定使用带有 $lookup 支持的 MongoDB。
所以我有三个集合:
1.餐厅
{
"_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"name" : "KFC",
"city" : "Lahore",
"area" : "Johar town",
"min_order" : "500",
"del_time" : "1 hour",
"del_fees" : "5",
"pre_order" : "no",
"rating_star" : "0",
"rating_no" : 0,
"status" : "1",
"working_hours" : {
"monday" : "2pm 6am",
"tuesday" : "6am 8pm",
"wednesday" : "9pm 5pm",
"thursday" : "3pm 6pm",
"friday" : "1pm 9pm",
"saturday" : "4pm 5pm",
"sunday" : "4pm 8pm"
},
"cuisines" : [
"fast food, pizza"
],
"payments" : [
"cash,credit card,paypal"
]
}
2。类别
"categories" : [
{
"_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"name" : "Breakfast",
"category_id" : "1",
"__v" : 0
},
{
"_id" : ObjectId("57c6a06021c8b8d04443aa7f"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"name" : "Special",
"category_id" : "2",
"__v" : 0
}
]
3。项目
"items" : [
{
"_id" : ObjectId("57c6da8cc8d053e8310dfe65"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"category_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"name" : "Water",
"price" : "55",
"rating" : "0",
"__v" : 0
},
{
"_id" : ObjectId("57c6da96c8d053e8310dfe66"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"category_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"name" : "Milk",
"price" : "55",
"rating" : "0",
"__v" : 0
}
]
我想要这样的 Json 响应输出
{
"_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"name" : "KFC",
"city" : "Lahore",
"area" : "Johar town",
"min_order" : "500",
"del_time" : "1 hour",
"del_fees" : "5",
"pre_order" : "no",
"rating_star" : "0",
"rating_no" : 0,
"status" : "1",
"working_hours" : {
"monday" : "2pm 6am",
"tuesday" : "6am 8pm",
"wednesday" : "9pm 5pm",
"thursday" : "3pm 6pm",
"friday" : "1pm 9pm",
"saturday" : "4pm 5pm",
"sunday" : "4pm 8pm"
},
"cuisines" : [
"fast food, pizza"
],
"payments" : [
"cash,credit card,paypal"
],
"__v" : 0,
"categories" : [{
"_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"name" : "Breakfast",
"category_id" : "1",
"__v" : 0,
"items" : [
{
"_id" : ObjectId("57c6da8cc8d053e8310dfe65"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"category_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"name" : "Water",
"price" : "55",
"rating" : "0",
"__v" : 0
},
{
"_id" : ObjectId("57c6da96c8d053e8310dfe66"),
"restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"),
"category_id" : ObjectId("57c6a05421c8b8d04443aa7e"),
"name" : "Milk",
"price" : "55",
"rating" : "0",
"__v" : 0
}
]
}]
}
我还是这样的
db.restaurants.aggregate([{
$lookup: {
from: "categories",
localField: "_id",
foreignField: "restaurant_id",
as: "categories"
}
}])
Restaurants 和 categories 工作正常,但我如何处理 categories 中的每个类别项目?
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query aggregation-framework