简体   繁体   中英

mongodb query and return specific collections

I'm trying to return all collections where field grade: 'Grade Two' , I've tried a number of queries but getting either error or nothing being returned. I want my query only return documents from the collection with 'Grade Two' , that should return only two docs.

I've tried the below queries:

db.users.find({grade: "Grade Two"})
db.users.find({}, {grade: "Grade Two"})
db.users.find({}, {profile: {grade: "Grade Two"}})

I'm getting error with message: "errmsg" : "Unsupported projection option: profile: { grade: \\"Grade Two\\" }",

{
    {
      "_id": "4YH8hDjNhN39CTtZh",
      "username": "philcee.philips",
      "emails": [
        {
          "address": "ph@gmail.com",
          "verified": false
        }
      ],
      "profile": {
        "name": {
          "firstname": "Philcee",
          "lastname": "Philips"
        },
        "gender": "Female",
        "nationality": "foo",
        "grade": "Grade Two"
      },
      "roles": {
        "__global_roles__": [
          "student"
        ]
      },
    {
          "_id": "8UH8hDjNhN39CTtm6",
          "username": "gibson.wilson",
          "emails": [
            {
              "address": "wil@gmail.com",
              "verified": false
            }
          ],
          "profile": {
            "name": {
              "firstname": "Gibson",
              "lastname": "Wilson"
            },
            "gender": "Male",
            "nationality": "bar",
            "grade": "Grade Two"
          },
          "roles": {
            "__global_roles__": [
              "student"
            ]
          },


    {
          "_id": "i7G8hDjKhN39CTYt9",
          "username": "daniel.jones",
          "emails": [
            {
              "address": "jones@gmail.com",
              "verified": false
            }
          ],
          "profile": {
            "name": {
              "firstname": "Daniel",
              "lastname": "Jones"
            },
            "gender": "Male",
            "nationality": "bar",
            "grade": "Grade One"
          },
          "roles": {
            "__global_roles__": [
              "student"
            ]
          }
    }

Is there another way to query for specific docs from the collection mentioned?

You can use .dot notation to find inside an object

db.users.find({ "profile.grade": "Grade Two" }) 

And to return specific field you can use projection in the second argument of the find query

db.users.find({ "profile.grade": "Grade Two" }, { "profile.grade": 1 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM