gpt4 book ai didi

arrays - MongoDB 获取文档的部分数组

转载 作者:可可西里 更新时间:2023-11-01 10:00:54 25 4
gpt4 key购买 nike

数据结构:

{
_id: '1',
'title: 'Blabla',
comments: [ {id:'3', type:'normal'} ,
{id: '4', type: 'admin'},
{id: '5', type: 'admin'},
{id: '6', type: 'admin'}
]
}

我想要得到的是一组 最后 5 条评论类型 admin:

{ comments: [{id:4, type:'admin'}, {id: '5', type: 'admin'}, {id: '6', type: 'admin'}] } 

我尝试过的:

db.collection('posts').find({_id: '1', 'comments.type':'admin'}
, {
comments:{$slice: -5},
comments:1, _id:0
})

但如果至少存在 1 个类型为 admin 的项目,它会返回空洞评论数组。

最佳答案

可以尝试使用聚合框架:

db.collection.aggregate([ 
{ $match: {_id: "1"} },
{ $unwind: "$comments" },
{ $match: { "comments.type": "admin" } },
{ $sort: { "comments.id": -1 } },
{ $limit: 5 }
])

这将生成 _id="1" 的最后 5 条评论的列表:

{ "_id" : "1", "title" : "abc", "comments" : { "id" : "7", "type" : "admin" } }
{ "_id" : "1", "title" : "abc", "comments" : { "id" : "6", "type" : "admin" } }
{ "_id" : "1", "title" : "abc", "comments" : { "id" : "5", "type" : "admin" } }
{ "_id" : "1", "title" : "abc", "comments" : { "id" : "4", "type" : "admin" } }
{ "_id" : "1", "title" : "abc", "comments" : { "id" : "3", "type" : "admin" } }

关于arrays - MongoDB 获取文档的部分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23537984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com