我在mongodb中有以下文档结构
{
"_id" : "123",
"first_name" : "Lorem",
"last_name" : "Ipsum",
"conversations" : {
"personal" : [
{
"last_message" : "Hello bar",
"last_read" : 1474456404
},
{
"last_message" : "Hello foo",
"last_read" : 1474456404
},
...
],
"group" : [
{
"last_message" : "Hello Everyone",
"last_read" : null
}
...
]
}
}我想要计算给定用户在last_read为空的子数组personal和group中的会话数量。我怎样才能做到这一点呢?
我试过了:
db.messages.aggregate(
[
{ $match: {"_id":"123", 'conversations.$.last_read': null }},
{
$group: {
{$size: "$conversations.personal"}, {$size: "$conversations.group"}
}
}
]
);但是没有得到他想要的输出。有什么更好的主意吗?
发布于 2016-09-22 01:15:01
以下查询计算personal和group数组下具有last_read值null的子文档数。
$concatArrays将多个数组合并为一个数组。它是在MongoDB 3.2中引入的。
db.collection.aggregate([
{ "$match": {"_id":"123", 'conversations.$.last_read': null }},
{ "$project":{"messages":{$concatArrays : ["$conversations.personal","$conversations.group"]}}},
{ "$unwind": "$messages"}, {$match:{"messages.last_read": null}},
{ "$group":{"_id":null, count: {$sum:1}}}
])示例结果:
{ "_id" : null, "count" : 3 }发布于 2016-09-22 00:04:15
根据问题,您似乎想要找出group array last_read包含null的位置。为此,您可以在聚合中使用$in,然后使用unwind personal数组并对数组进行计数。在聚合查询下面进行检查
db.collection.aggregate({
"$match": {
"conversations.group.last_read": {
"$in": [null]
}
}
}, {
"$unwind": "$conversations.personal"
}, {
"$group": {
"_id": "$_id",
"personalArrayCount": {
"$sum": 1
}
}
})https://stackoverflow.com/questions/39620555
复制相似问题