Mongodb 子阵和#x27;s长度
我希望统计用户是会话成员的所有会话中的未读消息。如果消息的id在readers数组中,则该消息由用户读取 下面返回存在未读消息的对话数。但如何计算所有未读邮件的数量Mongodb 子阵和#x27;s长度,mongodb,Mongodb,我希望统计用户是会话成员的所有会话中的未读消息。如果消息的id在readers数组中,则该消息由用户读取 下面返回存在未读消息的对话数。但如何计算所有未读邮件的数量 db.getCollection('conversations').count({ 'messages.readers': { $size: 1 }, //i.e. only the message author is in the message.readers array. 'members': { $in: [
db.getCollection('conversations').count({
'messages.readers': { $size: 1 }, //i.e. only the message author is in the message.readers array.
'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
})
我已经检查了聚合方法,但我不确定它是否是正确的方法。下面返回所有消息的数目
db.getCollection('conversations').aggregate([
{$match : {
'members': { $in: [ObjectId("59320e38188c5050ac99be8f")] }
}},
{$group: {_id: null, count: {$sum: {$size: "$messages"}}}},
])
您可以尝试下面的聚合管道 下面的查询将
$unwind
每个匹配对话中的所有消息,并在$sum
操作符中应用$cond
表达式来检查用户是否不在消息中。如果在$group
阶段存在匹配,则返回1,否则返回0
db.getCollection('conversations').aggregate([
{$match : {'members': ObjectId("59320e38188c5050ac99be8f") }},
{$unwind : "$messages"},
{$group: {_id: null, count: {$sum: {$cond: [{ $ne: ["messages.readers", ObjectId("59320e38188c5050ac99be8f")] }, 1, 0]}}}}
])
因此,$unwind
是一项昂贵的操作,不应优先于其他选项,但我认为在您的情况下,这是不可能的,$unwind
遵循$match
稍微好一点 您可以使用查询来检查用户是否在成员数组中,用户是否不在消息中。readers
数组后跟count。类似于db.getCollection('conversations').count({'members':ObjectId(“59320e38188c505ac99be8f”),“messages.readers:{$ne:ObjectId(“59320e3888c505ac99be8f”)}}})的东西当然可以了。
但是这会计算对话的数量,而不是未读的消息的数量。我想我设计这个数据库的方式是错误的。对不起,我没有真正注意到你在那里的所有不同部分。下面的查询将解开每个匹配对话中的每条消息,并应用查询筛选器。类似于db.getCollection('conversations').aggregate([{$match:{'members':ObjectId(“59320e38188c505ac99be8f”)},{$unwind:“$messages”},{$group:{{{u-id:null,count:{$sum:{$cond:[$ne:[“messages.readers”,ObjectId(“59320e3888c505ac99be8f”)}},1,0]}}
。我无法测试任何查询,因为您发布的数据是图像。请考虑将文档添加为文本。干杯请以aswers的形式发布。$REWIND是一个很好的功能。