mongodb查询并返回特定的集合

时间:2018-11-25 15:15:07

标签: mongodb mongodb-query

我正在尝试返回字段grade: 'Grade Two'处的所有集合,我尝试了许多查询,但均收到错误或未返回任何内容。我希望查询仅返回'Grade Two'集合中的文档,而该文档应该仅返回两个文档。

我尝试了以下查询:

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

我收到以下错误消息:"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"
            ]
          }
    }

还有另一种方法可以从提到的集合中查询特定文档吗?

1 个答案:

答案 0 :(得分:2)

您可以使用.dot表示法在对象内部进行查找

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

要返回特定字段,您可以在find查询的第二个参数中使用投影

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