问题
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
}
...
]
}
}
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?
I tried:
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?
回答1:
The following query counts the number of sub documents under personal
and group
arrays that have last_read
value null
.
$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}}}
])
Sample Result:
{ "_id" : null, "count" : 3 }
回答2:
As per question it looks like you want to find out where group array last_read
contains null
. For this you use $in
in aggregation and then unwind
personal
array and count the array. Check bellow aggregation query
db.collection.aggregate({
"$match": {
"conversations.group.last_read": {
"$in": [null]
}
}
}, {
"$unwind": "$conversations.personal"
}, {
"$group": {
"_id": "$_id",
"personalArrayCount": {
"$sum": 1
}
}
})
来源:https://stackoverflow.com/questions/39620555/count-elements-subdocument-that-match-a-given-criterion