2

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.