Node.js 具有ID列表的mongodb聚合
我得到了以下结论: 它扫描所有消息并按docId对它们进行分组,只返回每个组中最后更新的消息Node.js 具有ID列表的mongodb聚合,node.js,mongodb,aggregation,Node.js,Mongodb,Aggregation,我得到了以下结论: 它扫描所有消息并按docId对它们进行分组,只返回每个组中最后更新的消息 db.getCollection('Messages').aggregate([ { '$match': { docType: 'order' }}, { '$sort': { updatedAt: -1 } }, { '$group': { _id: '$docId', content: { '$first': '$content' }}}]) 返回- [ { "_id"
db.getCollection('Messages').aggregate([ { '$match': { docType: 'order' }}, { '$sort': { updatedAt: -1 } }, { '$group': { _id: '$docId', content: { '$first': '$content' }}}])
返回-
[
{
"_id" : "some id1",
"content" : "some msg1
}
/* 11 */
{
"_id" : "some id2",
"content" : "some msg2"
}
...
]
它按预期工作(不确定优化)
但现在我需要在上面再加一件事
在UI中,我得到了一个文档列表,我只需要显示每个文档的最新消息。但是我也得到了分页,所以我不需要为XXXXXX文档带来最后一条消息,只需要一页
基本上是这样的-
.find({'docId':{$in:['doc1', 'doc2', 'doc3'...]}}) - if the page had 3 items
但我不知道如何将所有这些结合起来
Message sample:
{
"_id": "11111"
"docType": "order",
"docId": "12345", - this is not unique there can be many messages for 1 docId
"content": "my message",
"updatedAt" "01/01/2020..."
}
添加
最后,我成功了
编辑:
或者实际上我认为最好将其添加为第一条管道,以便:
db.getCollection('Messages').aggregate([ { '$match': { docId: { '$in': ["5d79cba1-925b-416b-9408-6f4429d7c107", "8e31c748-c86d-407e-8d83-9810c8e23e3e"]} }}, { '$match': { docType: 'order' }}, { '$sort': { cAt: -1 } }, { '$group': { _id: '$docId', content: { '$first': '$content' }}}])
- 因为我是动态添加这些属性的,所以我得到了2$match属性。实际上,我不太确定使用$match+$和使用2个不同的$match(优化方面)有什么区别
db.getCollection('Messages').aggregate([ { '$match': { docId: { '$in': ["5d79cba1-925b-416b-9408-6f4429d7c107", "8e31c748-c86d-407e-8d83-9810c8e23e3e"]} }}, { '$match': { docType: 'order' }}, { '$sort': { cAt: -1 } }, { '$group': { _id: '$docId', content: { '$first': '$content' }}}])