我有一个收集" MessageCenter"我在哪里存储短信。
> db.MessageCenter.find().pretty()
{
"_id" : ObjectId("567edae40b38770a1c847ccc"),
"status" : 1,
"from" : "567edace0b38770a1c847ccb",
"name" : "abhishek rana",
"creationtime" : 1451154148.937,
"to" : "567ed86e0b387705ac92dcb2",
"message" : "hello clone......."
}
{
"_id" : ObjectId("567edb560b3877045c783f7a"),
"status" : 1,
"from" : "567edace0b38770a1c847ccb",
"name" : "abhishek rana",
"creationtime" : 1451154262.39,
"to" : "567ed86e0b387705ac92dcb2",
"message" : "hello clonee........................"
}
{
"_id" : ObjectId("567edb770b38770b30d51477"),
"status" : 0,
"from" : "567edace0b38770a1c847ccb",
"name" : "abhishek rana",
"creationtime" : 1451154295.595,
"to" : "567ed86e0b387705ac92dcb2",
"message" : "hello clonee........................"
}
现在我想知道是否有一种方法可以将对象输出返回为:
{
"from" : "567edace0b38770a1c847ccb",
"to" : "567ed86e0b387705ac92dcb2",
"name" : "abhishek rana",
"message" : [
{
"text" : "hello clone",
"creationtime" : 1451154148.937,
"status" : 1
},
{
"text" : "another text",
"creationtime" : 1451154148.937,
"status" : 1
}
]
}
因为我发现在一个数组中显示来自特定用户的所有消息而不是显示为多个对象更好。 我希望如果有解决办法。 感谢。
答案 0 :(得分:1)
使用.aggregate()
方法,$group
和$project
运算符。
db.MessageCenter.aggregate([
{ '$group': {
'_id': {
'from': '$from',
'to': '$to',
'name': '$name'
},
'message': {
'$push': {
'text': '$message',
'creationtime': '$creationtime',
'status': '$status'
}
}
}},
{ '$project': {
'from': '$_id.from',
'to': '$_id.to',
'name': '$_id.name',
'message': 1, '_id': 0
} }
])
产生
{
"message" : [
{
"text" : "hello clone.......",
"creationtime" : 1451154148.937,
"status" : 1
},
{
"text" : "hello clonee........................",
"creationtime" : 1451154262.39,
"status" : 1
},
{
"text" : "hello clonee........................",
"creationtime" : 1451154295.595,
"status" : 0
}
],
"from" : "567edace0b38770a1c847ccb",
"to" : "567ed86e0b387705ac92dcb2",
"name" : "abhishek rana"
}