Search code examples
arraysmongodbpymongo

MongoDB | Size of an array of a specific document given by id


I would like to understand how I can get the length (size) of a string array in a specific document that is found by _id passed to it.

For example:

document 1
_id: 1234
arr=["a","b","c","d"]

document 2
_id: 5678
arr=["e", "f"]

I would like to get the size of 'arr' by passing the _id "5678" What's would be the easiest way to do that?

Using pymongo

Thanks in advance!


Solution

  • Query

    • $match on _id
    • $size to get the array size
    • project to keep only the array-size

    Playmongo

    aggregate(
    [{"$match": {"_id": {"$eq": 5678}}},
     {"$project": {"_id": 0, "arr-size": {"$size": "$arr"}}}])