Mogodb $ cumulative empty array and multiple documents

mongodb has the document below:

> db.test.find({name:{$in:["abc","abc2"]}})
{ "_id" : 1, "name" : "abc", "scores" : [ ] }
{ "_id" : 2, "name" : "abc2", "scores" : [ 10, 20 ] }

I want to get the length of the points array for each document, how do I do this?

The done command below:

db.test.aggregate({$match:{name:"abc2"}}, {$unwind: "$scores"}, {$group: {_id:null, count:{$sum:1}}} )

Result:

{ "_id" : null, "count" : 2 }

But below the command:

db.test.aggregate({$match:{name:"abc"}}, {$unwind: "$scores"}, {$group: {_id:null, count:{$sum:1}}} )

Do not return anything. Question:

  • How can I get each length of points in 2 or more documents in one team?
  • Why does the result of the second command return nothing? and how should I check if the array is empty?
+4
source share
2 answers

, . $unwind , "", "", .

"0" "" , - .

MongoDB 2.6 $size:

db.test.aggregate([
    { "$match": { "name": "abc" } },
    { "$group": {
       "_id": null,
       "count": { "$sum": { "$size": "$scores" } }
    }}
])

:

db.test.aggregate([
    { "$match": { "name": "abc" } },
    { "$project": {
        "name": 1,
        "scores": {
            "$cond": [
                { "$eq": [ "$scores", [] ] },
                { "$const": [false] },
                "$scores"
            ]
        }
    }},
    { "$unwind": "$scores" },
    { "$group": {
        "_id": null,
        "count": { "$sum": {
            "$cond": [
                "$scores",
                1,
                0
            ]
        }}
    }}
])

, $size "" . "" false, , $unwind "" "" .

, false $cond "trinary", , 1 0 $sum .

" ".

+8

, _id $group, , _id.

, $match , , , ,

{'scores.0': {$exists: true}} {scores: {$not: {$size: 0}}} , :

db.test.aggregate([
    { "$match": {"scores.0": { "$exists": true } } },
    { "$unwind": "$scores" },
    {
        "$group": {
           "_id": "$_id",
           "count": { "$sum": 1 }
        }
    }
])
+1

All Articles