GyuPyo Shin
GyuPyo Shin

Reputation: 21

Array size function in mongodb

I'm beginner in MongoDB. I want to get an array size. I used as below:

db.users.aggregate([ 
{ $match: { id : "test_id" } },
{ $project : {
    id : 1, size : { $cond : {
            if : {$isArray: "$sentence"},
            then :{$size: "$sentence"},
            else: 0
            }
        }
    }
}

])

and I checked this

{"id" : "test_id", "size" : 4 }

but I want to use this in a function as below:

    function getSentenceNumber(in_id) { 
    var ret = db.users.aggregate([ 
        { $match: { id : in_id } },
        { $project : { 
            id : 1,
            size : {$cond : { if : {$isArray: "$sentence"}, then : {$size: "$sentence"}, else: 0 } }
        } }
    ]); 
    return ret.size;
}

To use db.users.update()

But I got "undefined".

Would someone help me?

Upvotes: 2

Views: 85

Answers (2)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

aggregate returns a Cursor. You can convert the cursor to an array and then take the first/last element. Your aggregation pipeline should return always one document only, so it should not matter.

function getSentenceNumber(in_id) { 
    var ret = db.users.aggregate([ 
        { $match: { id : in_id } },
        { $project : { 
            id : 1,
            size : {$cond : { if : {$isArray: "$sentence"}, then : {$size: "$sentence"}, else: 0 } }
    } }
   ]).toArray().pop(); 
   return ret.size;
}

However, if your aggregation pipeline may return more than just one document then have a look at Iterate a Cursor in the mongo Shell

Upvotes: 2

Use await for the DB call to complete.

async function getSentenceNumber(in_id) { 
    const ret = await db.users.aggregate([ 
        { $match: { id : in_id } },
        { $project : { 
            id : 1,
            size : {$cond : { if : {$isArray: "$sentence"}, then : {$size: "$sentence"}, else: 0 } }
        } }
    ]);
    console.log(ret); // aggregate will return array
    return (ret && ret[0] && ret[0].size) ? ret[0].size : 0;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Upvotes: 2

Related Questions