我正在尝试在mongoDB中执行以下操作:
获取每个用户的最新评论
以下是模型
{
"userId":"UserA",
"comments":[
{
"text":"abcd",
"created_at":"2015-10-09T03:34:46.701Z",
"commentNumber":1
},
{
"text":"abcde",
"created_at":"2015-10-09T04:34:46.701Z",
"commentNumber":2
}
]
}
我的预期输出是
{ "userId":"UserA" , "comments": [{
"text":"abcde",
"created_at":"2015-10-09T04:34:46.701Z",
"commentNumber":2
}]
},
{ "userId":"UserB" , "comments": [{
"text":"ghij",
"created_at":"2015-10-10T04:34:46.701Z",
"commentNumber":3
}]
}
我试着玩这样的东西,但它没有做我需要的东西
db.users.find({'comments.commentNumber':3},{'comments.$':1})
如果我在created_at上使用sort,那么它仍然会返回子文档的所有数组
有什么建议吗?
答案 0 :(得分:1)
如果"最新"总是"最后" (当附加到数组时应该是这样)然后你希望$slice
返回最后一个数组元素:
db.users.find({},{ "comments": { "$slice": -1 } })
如果由于某种原因这不是那个顺序,那么你需要用.aggregate()
来操纵数组:
db.users.aggregate([
{ "$unwind": "$comments" },
{ "$sort": { "comments.created_at": 1 } },
{ "$group": {
"_id": "$_id",
"userId": { "$first": "$userId" },
"comments": { "$last": "$comments" }
}},
{ "$group": {
"_id": "$_id",
"userId": { "$first": "$userId" },
"comments": { "$push": "$comments" }
}}
])