【问题标题】:mongodb query and return specific collectionsmongodb查询并返回特定集合
【发布时间】:2018-11-28 00:24:20
【问题描述】:

我正在尝试返回字段 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"
            ]
          }
    }

还有其他方法可以从上述集合中查询特定文档吗?

【问题讨论】:

  • 使用.dot 表示法db.users.find({ "profile.grade": "Grade Two" }) 和投影db.users.find({ "profile.grade": "Grade Two" }, { "profile.grade": 1 })
  • 太好了,谢谢。这真的很有帮助。现在一切都好。

标签: mongodb mongodb-query


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2017-09-15
    • 2015-07-20
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多