我可以通过查询在特定文档中找到子文档
await Conversations.find(
{_id: room_id,"messages.sender": user_id}, function(err, success){
if(success){
console.log("success",success)
for (r of success){
console.log(r);
}
}
})
但是上面的查询找到了该文档中的所有消息。解决此问题而不使用聚合的最佳方法是什么?我必须写一个修改查询
我的收藏集如下:
{"data":{"_id":"5c2d4c2b116da2322616c387","messages":[{"msg_type":"text","time_created":"2019-01-03T00:03:25.055Z","_id":"5c2d514d70407c00102a67b2","sender":"0360a5ac-4b51-4c4d-b8b6-c6bad088135b","content":"Hi","seen":true},{"msg_type":"text","time_created":"2019-01-03T00:04:27.583Z","_id":"5c2d518b70407c00102a67b3","sender":"47a36731-f245-4c62-8a34-d7bc034634c9","content":"hi","seen":true},{"msg_type":"text","time_created":"2019-01-03T00:04:33.422Z","_id":"5c2d519170407c00102a67b4","sender":"0360a5ac-4b51-4c4d-b8b6-c6bad088135b","content":"Great","seen":true},{"msg_type":"text","time_created":"2019-01-03T00:04:39.487Z","_id":"5c2d519770407c00102a67b5","sender":"0360a5ac-4b51-4c4d-b8b6-c6bad088135b","content":"We have some conversations","seen":true}]}
答案 0 :(得分:0)
您正在尝试查询一系列嵌入式文档。
let query = {
_id: room_id,
{ messages: { $elemMatch: { sender: user_id } } }
}
await Conversations.find(query, function(err, success){
if(success) {
console.log("success",success)
for (r of success) {
console.log(r);
}
}
})
您可以阅读有关如何查询一系列嵌入式文档here的信息。