1

I have a JSON in MongoDB with collection name StudentData as:

"data" : {
  "students":{
      "A":{
        "roll":"11",
        "otherDetails":{
            "name":"AAA"
        }
      },
      "B":{
        "roll":"12",
        "otherDetails":{
            "name":"BBB"
        }
      },
      "C":{
        "roll":"13",
        "otherDetails":{
            "name":"CCC"
        }
      },
      "D":{
        "roll":"14",
        "otherDetails":{
            "name":"DDD"
        }
      }
  }
}

How can I fetch all students A, I tried the following db.StudentData.find({"data.students":"A"}) but it is returning nothing .

I am trying to get this:

{
   "roll":"11",
   "otherDetails":{
   "name":"AAA"
  }
}

What could be it's Java Equivalent and Mongo equivalent queries?

2 Answers 2

1

A is object in your data but you are fetching it as a value. So, it gives you nothing. Try this:

db.collection.find({},
{
  "data.students.A": 1
})
Sign up to request clarification or add additional context in comments.

4 Comments

It is somewhat working . What is the meaning of 1 here ??
It means that you are projecting the field "data.students.A" only while fetching list of data.
Thanks . Can you let me know how do I convert it into Java equivalent using MongoDb criteria ?
collection.find(new BasicDBObject(), new BasicDBObject("data.students.A", 1));
0

It is a simple approach suggested by @MilanRegmi

Though, I just would like to add other possible ways using aggregation.

db.collections.aggregate([
  { $addFields: { studentsList: { $objectToArray: "$data.students" } } },
  { $match: { "studentsList.k": "A" }},
  { $project: {
    students: { $filter: {
        input: '$studentsList',
        as: 'student',
        cond: { $eq: [ '$$student.k', 'A' ]}
    }},
    _id: 0
  }},
  { $unwind: "$students" }, // Not required if you are ok with having some nested array
  { $replaceRoot: { newRoot: "$students.v" }} // Not required if you are ok with having some nested array
])

And one more optimized query is:

db.collection.aggregate([
  { $addFields: { studentsList: { $objectToArray: "$data.students" } } },
  { $unwind: "$studentsList" },
  { $match: { "studentsList.k": "A" }},
  { $replaceRoot: { newRoot: "$studentsList.v" }} // Not required if you are ok with having object with some other fields
])

Output: (For both queries)

/* 1 */
{
    "roll" : "11",
    "otherDetails" : {
        "name" : "AAA"
    }
}

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.