mongodb - MongoDB:尝试根据嵌套子文档中匹配条件的计数更新字段
问题描述
我有下面的嵌套文档数组并尝试更新“readCounter”(这是数字)。我想将“readCounter”设置为匹配条件的文档计数:“userId”:“naveen”和“otherUserIds.otherUserId”:“ashwini”和“messages.sentBy”:“ashwini”。在以下情况下,上述条件的 readCounter 应设置为“2”。请帮助我使用 MongoDB 查询来更新“readCounter”。
我使用以下查询进行更新,但它给出了错误的结果。
AllChats.aggregate(
[
{
$match: {
userId: details.userId,
"otherUserIds.otherUserId": details.otherUserId,
"messages.sentBy": details.otherUserId
}
},
{
$set: { $count: "otherUserIds.$.msgReadCounter"}
}
]
);
下面是数据库数据:
AllChats = [{
"_id" : ObjectId("5f43fb76167f53d3d46b52ef"),
"userId" : "naveen",
"otherUserIds" : [
{
"otherUserId" : "ashwini",
"readCounter" : 0,
"messages" : [
{
"msg" : "Hi Naveen",
"sentBy" : "ashwini"
},
{
"msg" : "Hi Ashwini",
"sentBy" : "naveen"
},
{
"msg" : "How are you today",
"sentBy" : "ashwini"
},
{
"msg" : "I'm good",
"sentBy" : "naveen"
}
]
},
{
"otherUserId" : "testuser",
"readCounter" : 0,
"messages" : [
{
"msg" : "Hi naveen",
"sentBy" : "testuser"
},
{
"msg" : "Im good",
"sentBy" : "naveen"
},
{
"msg" : "how are you today",
"sentBy" : "testuser"
},
{
"msg" : "how are you testuser",
"sentBy" : "naveen"
}
]
}
]
}
{
"_id" : ObjectId("5f440e5e167f53d3d46b52f0"),
"userId" : "ashwini",
"otherUserIds" : [
{
"otherUserId" : "naveen",
"readCounter" : 0,
"message" : [
{
"msg" : "Hi Naveen",
"sentBy" : "ashwini"
},
{
"msg" : "Hi Ashwini",
"sentBy" : "naveen"
},
{
"msg" : "How are you today",
"sentBy" : "ashwini"
},
{
"msg" : "I'm good",
"sentBy" : "naveen"
}
]
}
]
}]
解决方案
我自己找到了解决方案,但它很昂贵。它涉及两个独立的数据库查询,因此我愿意接受更好的解决方案。
try{
let counter = await AllChats.aggregate([
{$match: {userId: details.userId}},
{$unwind: "$otherUserIds"},
{$match: {"otherUserIds.otherUserId": details.otherUserId}},
{$unwind: "$otherUserIds.messages"},
{$match: {"otherUserIds.messages.sentBy": details.otherUserId}},
{$count: "counter"}
]);
console.log(counter[0]);
if(counter[0] !== undefined){
await AllChats.findOneAndUpdate(
{userId: details.userId},
{$set: {"otherUserIds.$[elem].msgReadCounter": counter[0].counter}},
{arrayFilters: [{"elem.otherUserId": details.otherUserId}]}
);
console.log("Updated message read counter");
}
} catch(err){
console.log(err);
}
推荐阅读
- c++ - 1 到 1000 的并行数之和
- angular - .toJson() 将日期转换为 UTC
- excel - 引用另一个工作表中的单元格,但指定某个单元格中的单元格编号
- azure - IMAP 扩展不工作 Linux Azure Web 应用程序
- php - Magento ?SID 键被插入到包含散列的 wordpress 锚标记中
- python - Azure 错误:授权失败
- python - python ssh paramiko 保存到文件
- javascript - 角度 4. 无法打开应用程序
- c# - 扩展器标题组描述另一个控件中的额外摘要
- android - 每当点击 RecyclerView 中的透明项目时,背景广告点击不起作用