我有两个收集点集合和用户集合,我想根据用户ID进行聚合。
这里我正在尝试聚合,一切正常但我需要修改结果
db.points.aggregate([
$match: {
store: "001",
date: {$lte: ISODate("2017-11-10T08:15:39.736Z"), $gte: ISODate("2017-11-10T08:15:39.736Z")}
},
{
$lookup: {
from: "users",
localField: "userid",
foreignField: "_id",
as: "user"
}
},
{
$project:
{
_id:0,
"userdata.purchasedetails.purchaseid" : 1,
"userdata.purchasedetails.data" : 1,
usermobinumber: { "$arrayElemAt": [ "$user.mobinumber", 0 ] }
}}
像这样存储的数据
{
"userpoint": "2",
"date":ISODate("2017-11-10T08:15:39.736Z"),
"store":"001",
"userid":[
objectID("5a7565ug8945rt67"),
objectID("8a35553d3446rt78")
],
"userdata":{
"profile":[],
"purchasedetails":
[{
"purchaseid":"dj04944",
"data":"awe"
}]
}
}
得到这样的结果:
{
"usermobinumber":"9611",
"userdata":{
"purchasedetails":
[{
"purchaseid":"dj04944",
"data":"awe"
}]
}
我期待的结果:
我不想要树结构输出我需要这样
{
"usermobinumber":"9611",
"purchaseid":"dj04944",
"data":"awe"
}
我该怎么做才能帮助我
答案 0 :(得分:1)
你可以在这里做点什么,
db.points.aggregate([
//Whatever you are doing here now (lookup and match)
{
$project:{
"usermobinumber":"$usermobinumber",
"purchaseid":"$userdata.purchasedetails.purchaseid"
}
}
])
这会给你:
{
"usermobinumber" : "9611",
"purchaseid" : [
"dj04944"
]
}
修改强>
db.points.aggregate([
//Whatever you are doing here now (lookup and match)
{
{
$project:{
"usermobinumber":"$usermobinumber",
"purchaseid":"$userdata.purchasedetails.purchaseid",
"data":"$userdata.purchasedetails.data"
}
}
}
])
这会给你
{
"usermobinumber":"9611",
"purchaseid":["dj04944"],
"data":["awe"]
}
purchaseid
和data
是数组,因为purchasedetails
是一个数组。
答案 1 :(得分:0)
您可以添加$ unwind阶段来展平结果....