0

I want to be able to specify in my MongoDB query to, for each document, return the number of elements in a specific sub field (var_2 in this case), instead of the whole array. Example document:

{
  "_id": "abc123",
  "var_1": "A",
  "var_2": [
    "A", 
    "B", 
    "C"
  ]
}

I have tried this but it returns the whole array:

db.collection.find({var_1: "A"}, {var_1: 1, var_2: 1})

Desired output:

{
"_id": "abc123",
"var_1": "A",
"var_2": 3
}

Thanks in advance!

1 Answer 1

1

You can retrieve the size of your array by using $size but with an aggregation since it's not supported in find' projection:

db.your_collection.aggregate([
  {
    "$match": {
      var_1: "A"
    }
  },
  {
    "$project": {
      "var_1": 1,
      "var_2": {
        "$size": "$var_2"
      }
    }
  }
])

Result

[
  {
    "_id": "abc123",
    "var_1": "A",
    "var_2": 3
  }
]
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.