1

The sample structure is as follows:

{
    "_id": 1,
    "College_name" : "abcdef"
    "Students": [
{
  "name": "a",
  "Grade": "First"
},
{
  "name": "b",
  "Grade": "Second"
},
{
  "name": "c",
  "Grade": "First"
},
{
  "name": "d",
  "Grade": "First"

}
]
}

What I am not getting is - I want to get all ("Grade" : "First") objects in the array and insert only ("Grade" : "First") objects to other collection where ("College_name" : "abcdef"). What is the optimal solution for this? Is this possible through aggregation?? Please help me out to solve this.

2 Answers 2

0

You can fetch the data with {"Grade": "First"} either using aggregation or mongo query -

Aggregation query -

db.coll.aggregate([{'$match':{"Students.Grade":"First"}}, {$project: {"_id":1, "College_name":1}}])

Mongo Query -

db.coll.find({"Students.Grade":"First"}, {"College_name":1})

After that you can insert the data to other collection.

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

2 Comments

Yes this works. But i want to retrieve only the objects with {"Grade": "First"} where ("College_name" : "abcdef"). i.e., output should not contain the sub document with (name : "b").
Using $in and $ projection, we will get only the first matched element in the array. How would we get multiple matched elements??
0

Answer to this question is in the link:

query to retrieve multiple objects in an array in mongodb

i.e., Aggregation query will have 4 pipeline operators:

  [match, unwind, match, group]

and then can be inserted to the other collection.

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.