1

I need the document in a collection that has the least array size of a field among all. Document looks as follows:

{
    "_id": ObjectId("jsd273rsdjkvn847ckjnas74"),
    "associatedUsers": [
        ObjectId("jsd273rsdjkvn847ckjnas75"),
        ObjectId("jsd273rsdjkvn847ckjnas76")
    ]
}

Out of all the documents in MongoDB, I need to find the one with least number of associatedUsers in its array. Basically the one with shortest array length.

1 Answer 1

2

You can use $addFields to calculate new field based on array $size and then use $sort along with $limit to get the document with smallest array:

db.collection.aggregate([
    {
        $addFields: {
            size: { $size: "$associatedUsers" }
        }
    },
    {
        $sort: { size: 1 }
    },
    {
        $limit: 1
    }
])

Mongo Playground

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

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.