代码之家  ›  专栏  ›  技术社区  ›  Israel Z Kollie

MongoDB查询并返回特定集合

  •  1
  • Israel Z Kollie  · 技术社区  · 6 年前

    我正在尝试返回所有收藏的Where字段 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 回复  |  直到 6 年前
        1
  •  2
  •   Ashh    6 年前

    可以使用.dot符号在对象内部查找

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

    要返回特定字段,可以在 find 查询

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