我是mongodb的新手,对于应用程序,我有架构,
{
date: "date",
data:"encrypted data",
sender:"sender",
receiver:"receiver"
}
我希望在一个对象中有一组记录,其中发送者/接收者名称的组别不等于特定值。 对于前。
{
date: "date",
data:"encrypted data",
sender:"xyz",
receiver:"abc"
},
{
date: "date",
data:"encrypted data",
sender:"abc",
receiver:"xyz"
},
{
date: "date",
data:"encrypted data",
sender:"pqr",
receiver:"abc"
},
{
date: "date",
data:"encrypted data",
sender:"abc",
receiver:"pqr"
},
{
date: "date",
data:"encrypted data",
sender:"pqr",
receiver:"xyz"
},
{
date: "date",
data:"encrypted data",
sender:"xyz",
receiver:"pqr"
}
当我使用find(abc)和一些组函数时,我需要采用以下格式的数据。
{
xyz:[
{
date: "date",
data:"encrypted data",
sender:"xyz",
receiver:"abc"
},
{
date: "date",
data:"encrypted data",
sender:"abc",
receiver:"xyz"
}
],
pqr:[
{
date: "date",
data:"encrypted data",
sender:"pqr",
receiver:"abc"
},
{
date: "date",
data:"encrypted data",
sender:"abc",
receiver:"pqr"
}
]
}
如何使用$ group或mongodb的任何其他功能,以给定格式提供结果?
答案 0 :(得分:1)
使用 aggregation framework 来获得所需的结果。聚合管道只有初始$project
阶段,它会重新整形流中的每个文档,例如只删除mongodb的_id
字段,因为您在输出中不需要它。
下一个管道阶段是$group
运算符步骤,它按指定的标识符receiver
键对前一个$project
阶段的输入文档进行分组,并应用累加器表达式$addToSet
只需将系统变量$$ROOT
添加到数组data
的每个组。
获得聚合管道后,您需要使用其光标的forEach()
方法迭代聚合结果以创建最终结果对象:
var result = {};
db.collection.aggregate([
{
"$project": {
"_id": 0,
"date": 1,
"data": 1,
"sender": 1,
"receiver": 1
}
},
{
"$group": {
"_id": "$receiver",
"data": {
"$addToSet": "$$ROOT"
}
}
}
]).forEach(function (doc){
result[doc._id] = doc.data
});
printjson(result);
<强>输出强>:
{
"pqr" : [
{
"date" : "date",
"data" : "encrypted data",
"sender" : "xyz",
"receiver" : "pqr"
},
{
"date" : "date",
"data" : "encrypted data",
"sender" : "abc",
"receiver" : "pqr"
}
],
"xyz" : [
{
"date" : "date",
"data" : "encrypted data",
"sender" : "pqr",
"receiver" : "xyz"
},
{
"date" : "date",
"data" : "encrypted data",
"sender" : "abc",
"receiver" : "xyz"
}
],
"abc" : [
{
"date" : "date",
"data" : "encrypted data",
"sender" : "pqr",
"receiver" : "abc"
},
{
"date" : "date",
"data" : "encrypted data",
"sender" : "xyz",
"receiver" : "abc"
}
]
}