计算符合给定条件的子文档元素 [英] 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
}
...
]
}
}
我想计算给定用户的 last_read
为空的子数组 personal
和 group
的对话数.请问我怎样才能做到这一点?
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屋!
查看全文