Mongodb 如何检索mongo';s受嵌套属性限制的文档
设想以下数据结构:Mongodb 如何检索mongo';s受嵌套属性限制的文档,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,设想以下数据结构: [ { "_id": ..., "title": "Post #1", "date": "2019-01-01" "comments": [ { "_id": ..., "text": "Comment #1 on #1", "date": "2019-01-01" } ] }, { "_
[
{
"_id": ...,
"title": "Post #1",
"date": "2019-01-01"
"comments": [
{
"_id": ...,
"text": "Comment #1 on #1",
"date": "2019-01-01"
}
]
},
{
"_id": ...,
"title": "Post #2",
"date": "2019-02-01"
"comments": [
{
"_id": ...,
"text": "Comment #1 on #2",
"date": "2019-02-01" // too old
},
{
"_id": ...,
"text": "Comment #2 on #2",
"date": "2019-02-10"
},
{
"_id": ...,
"text": "Comment #3 on #2",
"date": "2019-02-20"
}
]
},
{
"_id": ...,
"title": "Post #3",
"date": "2019-02-12"
"comments": [
{
"_id": ...,
"text": "Comment #1 on #3",
"date": "2019-02-15"
}
]
},
{
"_id": ...,
"title": "Post #4",
"date": "2019-03-01"
"comments": [] // none
}
]
我想在帖子中展示3条最新评论
应该是:
- 评论#1对#3
- 评论#3对#2
- 评论#2对#2
[
{
"_id": ...,
"title": "Post #3",
"date": "2019-02-12"
"comments": [
{
"_id": ...,
"text": "Comment #1 on #3",
"date": "2019-02-15"
}
]
},
{
"_id": ...,
"title": "Post #2",
"date": "2019-02-01"
"comments": [
{
"_id": ...,
"text": "Comment #3 on #2",
"date": "2019-02-20"
},
{
"_id": ...,
"text": "Comment #2 on #2",
"date": "2019-02-10"
}
]
}
]
是否可以在Mongo上执行此类搜索?
需要注意的重要一点是:“限制”是3,但它返回了2个文档/帖子,总共有3条评论。试试这个:
db.collection_name.aggregate([{
$unwind : "$comments"
},{
$sort : {"date" : 1, "comments.date" : 1}
},{
$limit : 3
},{
$group :{
_id : "$_id",
title : {$first : "$title"},
date : {$first : "$date"},
comments : {$push : "$comments"},
}
}])
1:“未知的组运算符“$post”。然后我试着用“post”代替2:字段“comments”必须是累加器对象它应该是
push
,而不是post
。我已经更新了我的答案,请检查。是的,它有效。我只需要修复排序:$sort:{“comments.date”:-1}