2

I have a bunch of documents in the following format:

{
    _id: "5b38c85f213751038ff4d0bb",
    classes: [
      {
        _id: "5b38c85f21375103ytg65ju7",
        standard: "12",
        numberOfStudents: 45
      },
      {
        _id: "5b38c85f2137510370987hgd",
        standard: "11",
        numberOfStudents: 51
      },
    ]
}

I want to:

  1. Search the collection of documents by the _id and a particular class's _id.
  2. Update the numberOfStudents for that class.
  3. Return only the class object.

So for _id: "5b38c85f213751038ff4d0bb" & classes._id: "5b38c85f21375103ytg65ju7", updating the numberOfStudents: 43 the result I'm expecting is:

{
  _id: "5b38c85f21375103ytg65ju7",
  standard: "12",
  numberOfStudents: 43
}

I've tried a couple of things but they all return the whole document but not the way I want it to be.

2
  • what criteria you do have to update numberOfStudents? Commented Jul 2, 2018 at 7:18
  • It'll be a user defined value so it could be any number. We just have to update it on the basis of the two ids. Commented Jul 2, 2018 at 7:19

1 Answer 1

1

You can try below aggregation

db.collection.aggregate([
  { "$match": { "_id": "5b38c85f213751038ff4d0bb" }},
  { "$addFields": {
    "classes": {
      "$filter": {
        "input": "$classes",
        "as": "class",
        "cond": {
          "$eq": [
            "$$class._id",
            "5b38c85f21375103ytg65ju7"
          ]
        }
      }
    }
  }},
  { "$unwind": "$classes" },
  { "$replaceRoot": { "newRoot": "$classes" }},
  { "$project": {
    "_id": 1,
    "numberOfStudents": { "$literal": 43 },
    "standard": 1
  }}
])

Output

[
  {
    "_id": "5b38c85f21375103ytg65ju7",
    "numberOfStudents": 43,
    "standard": "12"
  }
]

Try it here

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

9 Comments

So I went with your approach and it returns a blank array.
I have given you the try section... please have a look
Yeah thats the strange part that it works on the playground but not on my machine.
what is your mongodb version ?
Then it should work and it should work for mongoose as well... I think you are doing a minor mistake somewhere in the code either is could be with database or something else... try to find it
|

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.