鉴于此数据集和此mongodb,如何正确地将此聚合转换为Mongoose?
我已经包含了使用mongoose的代码,但是我想知道这是否是正确的方法,如果可以改进这种聚合?
感谢。
db.cars.aggregate(
//De-normalized the nested array of accounts
{"$unwind": "$accounts"},
//De-normalized the nested array of cars
{"$unwind": "$accounts.cars"},
//match carId to 3C
{"$match": {"accounts.cars.carId" : "3C"}},
//Project the accounts.cars object only
{"$project" : {"accounts.cars" : 1}}
).pretty();
我正在努力改进的Mongoose版本:
Car.aggregate()
.unwind('accounts')
.unwind('accounts.cars')
.match({'accounts.cars.carId' : "3C"})
.project({"accounts.cars": 1, _id: 0})
.exec(function (err, carsObj) {});
和数据集(汽车):
{
"_id" : ObjectId("56223329b64f07a40ef1c15c"),
"username" : "john",
"email" : "john@john.com",
"accounts" : [
{
"_id" : ObjectId("56322329b61f07a40ef1c15d"),
"cars" : [
{
"carId" : "6A",
"_id" : ObjectId("56323329b64f07a40ef1c15e")
},
{
"carId" : "6B",
"_id" : ObjectId("56323329b64f07a40ef1c15e")
}
]
}
]
},
{
"_id" : ObjectId("56223125b64f07a40ef1c15c"),
"username" : "paul",
"email" : "paul@paul.com",
"accounts" : [
{
"_id" : ObjectId("5154729b61f07a40ef1c15d"),
"cars" : [
{
"carId" : "5B",
"_id" : ObjectId("56323329854f07a40ef1c15e")
}
]
},
{
"_id" : ObjectId("56322117b61f07a40ef1c15d"),
"cars" : [
{
"carId" : "6G",
"_id" : ObjectId("51212929b64f07a40ef1c15e")
},
{
"carId" : "3C",
"_id" : ObjectId("51273329b64f07a40ef1c15e")
},
{
"carId" : "4N",
"_id" : ObjectId("51241279b64f07a40ef1c15e")
}
]
}
]
}
聚合返回的内容是:
[
{ accounts:
{ cars:
{
"carId" : "3C",
"_id" : ObjectId("51273329b64f07a40ef1c15e")
}
}
}
]