问题描述
我有下面的嵌套文档数组,并尝试更新“ 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",{
"msg" : "I'm good","sentBy" : "naveen"
}
]
},{
"otherUserId" : "testuser","messages" : [
{
"msg" : "Hi naveen","sentBy" : "testuser"
},{
"msg" : "Im good",{
"msg" : "how are you today",{
"msg" : "how are you testuser","sentBy" : "naveen"
}
]
}
]
}
{
"_id" : ObjectId("5f440e5e167f53d3d46b52f0"),"userId" : "ashwini","otherUserIds" : [
{
"otherUserId" : "naveen","message" : [
{
"msg" : "Hi Naveen","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);
}