Mongodb查找具有条件的不同计数
如何在mongodb中进行选择Mongodb查找具有条件的不同计数,mongodb,Mongodb,如何在mongodb中进行选择 Select room(distinct), count(where read =1) from chat where from = "1" or to ="1" 这是我的json { "_id" : ObjectId("595da6052008fc2213db32f6"), "room" : "1_40", "from" : "1", "to" : "40", "user_name" : "Tran Cot",
Select room(distinct), count(where read =1)
from chat
where from = "1" or to ="1"
这是我的json
{
"_id" : ObjectId("595da6052008fc2213db32f6"),
"room" : "1_40",
"from" : "1",
"to" : "40",
"user_name" : "Tran Cot",
"mes" : "hgfd",
"time" : 1499309573832,
"read" : 1
}
如果您想要每个房间的总阅读邮件数 使用 更新
这绝大多数都不是问题。“from”和“to”成为一个真正的问题,因为您的所有数据都表示为“字符串”。因此,您无法真正对“字符串”进行数字比较。你们真的应该先修正你们的数据,然后把应该是数字的东西变成数字。很抱歉,那个是字符串对字符串的比较,你们误解了我的代码。字符串不起作用。修复您的数据。这应该足够简单,不会误解。好吧,假设我的json是数字1,而不是字符串“1”。怎么用?thanxit不是from和to的问题,因为我可以进行如下查询。db.chat.distinct(“room”、{$or:[{from:“41”}、{to:“41”}]})返回值[“1_41”、“40_41”]得到它:db.chat.aggregate([{$match:{$or:[{from:“1”}、{to:“1”}},{$group:{id:“$room”,count$sum:{$sum:{$sum:{$cond:{$read if:{$eq:[“$read false]}}),然后:1,否则:0}})
db.chat.aggregate([
{ $match: { $or: [{ from: "41" }, { to: "41" }] } },
{ $group: {
_id: "$room",
count: {
$sum: {
$cond: { if: $eq: ["$read", false], then: 1, else: 0 }
}
}
}}
]);