0

I've a complex collection in MongoDB. In this, I want to query departments data based on the subDeptName. I used query like below db.getCollection('users').find({"departments.subDeptName" : "Java"}), but its fetching all the array elements of the department. I only wants to query such department where "subDeptName" : "Java". How can we do that ?

{
    "firstName" : "John",
    "lastName" : "Kerr",
    "email" : "john.kerr@gmail.com",
    "countryName" : "USA",
    "usRestrictionSw" : "N",
    "status" : "Active",
    "effDate" : ISODate("2012-08-24T01:46:33.000Z"),
    "departments" : [ 
        {
            "subDeptCd" : "AB",
            "languageCd" : "en",
            "desc" : "Development Group",
            "subDeptName" : "Java",
            "status" : "Active"
        }, 
        {
            "subDivisionAlpha2Cd" : "KG",
            "subDivisionCd" : "B",
            "languageCd" : "ru",
            "desc" : "Testing Group",
            "subDeptName" : "Python",
            "status" : "Active"
        }, 
        ..........
        ..........
        ..........
        ..........
    }
}
PAA
  • 1
  • 46
  • 174
  • 282
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Ashh May 10 '19 at 10:08

2 Answers2

1
db.getCollection('users').find({"departments.subDeptName" : "Java"})

Will match all users with a sub deperament java.

Easiest way to achieve the result you want is this:

 db.getCollection('users').aggregate([
           {
             $unwind: "$departments"
           },
           { 
             $match: {
                "departments.subDeptName" : "Java"
           }
 ])

Now you can also add a $project phase to get only the specific fields you want.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
-1

Try this:-

db.getCollection('users').find({"departments.subDeptName" : "Java"})

i have checked this on command line work fine. Please check your mongo version and mongo shell version

mongod --version (check mongo version)

mongo --version // check mongo shell version.

And also check error log for have unother issue.

Amarat
  • 602
  • 5
  • 11