符合给定条件的元素子文档计数 [英] Count Elements SubDocument that match a given criterion
本文介绍了符合给定条件的元素子文档计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongodb中具有以下文档结构
I have the following document structure in 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
}
...
]
}
}
对于给定的用户,我想计算子数组personal
和group
(其中last_read
为空)中的会话数.请问我该如何实现?
I want to count the number of conversations from the sub arrays, personal
and group
where the last_read
is null, for a given user. Please how can I achieve this?
我尝试过:
db.messages.aggregate(
[
{ $match: {"_id":"123", 'conversations.$.last_read': null }},
{
$group: {
{$size: "$conversations.personal"}, {$size: "$conversations.group"}
}
}
]
);
但是没有得到他想要的输出.有更好的主意吗?
but didn't get he desired output. Any better ideas, please?
推荐答案
以下查询计算personal
和group
数组下具有last_read
值null
的子文档的数量.
The following query counts the number of sub documents under personal
and group
arrays that have last_read
value null
.
$concatArrays
将多个数组组合为一个数组.它是在MongoDB 3.2中引入的.
$concatArrays
combines multiple arrays into a single one. It was introduced in 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 }
这篇关于符合给定条件的元素子文档计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文