【问题标题】:Error in Projection using find() method使用 find() 方法进行投影时出错
【发布时间】:2015-12-11 13:35:23
【问题描述】:

我是 MongoDB 的新手。当我遇到问题时,我在 mongo 中尝试基本的东西。我搜索了它,但找不到任何满意的答案。

我有一个非常简单的集合,名为“用户”,其中包含一些人的姓名和年龄。下面是db.users.find()的输出

{ "_id" : ObjectId("566acc0442fea953b8d94a7e"), "name" : "gabriel", "age" : 22 }
{ "_id" : ObjectId("566acc0442fea953b8d94a7f"), "name" : "andy", "age" : 10 }
{ "_id" : ObjectId("566acc1342fea953b8d94a80"), "name" : "henry", "age" : 27 }
{ "_id" : ObjectId("566acc1342fea953b8d94a81"), "name" : "william", "age" : 19 }
{ "_id" : ObjectId("566acc3242fea953b8d94a82"), "name" : "sandra", "age" : 20 }
{ "_id" : ObjectId("566acc3242fea953b8d94a83"), "name" : "tom", "age" : 24 }

现在,我正在尝试对其应用不同的投影。前两个是:

db.users.find({}, {"name":1, "age":1})

{ "_id" : ObjectId("566acc0442fea953b8d94a7e"), "name" : "gabriel", "age" : 22 }
{ "_id" : ObjectId("566acc0442fea953b8d94a7f"), "name" : "andy", "age" : 10 }
{ "_id" : ObjectId("566acc1342fea953b8d94a80"), "name" : "henry", "age" : 27 }
{ "_id" : ObjectId("566acc1342fea953b8d94a81"), "name" : "william", "age" : 19 }
{ "_id" : ObjectId("566acc3242fea953b8d94a82"), "name" : "sandra", "age" : 20 }
{ "_id" : ObjectId("566acc3242fea953b8d94a83"), "name" : "tom", "age" : 24 }

db.users.find({}, {"name":0, "age":0})

{ "_id" : ObjectId("566acc0442fea953b8d94a7e") }
{ "_id" : ObjectId("566acc0442fea953b8d94a7f") }
{ "_id" : ObjectId("566acc1342fea953b8d94a80") }
{ "_id" : ObjectId("566acc1342fea953b8d94a81") }
{ "_id" : ObjectId("566acc3242fea953b8d94a82") }
{ "_id" : ObjectId("566acc3242fea953b8d94a83") }

工作正常,但是

db.users.find({}, {"name":0, "age":1})

错误:错误:{ "$err" : "无法规范化查询:BadValue Projection 不能同时包含包含和排除。", “代码”:17287 }

失败并给出错误,如上所示。我搜索了如果投影中存在冲突条件可能会出现问题,但我认为我的方法调用中没有类似的东西。是否有一些规则,例如 find 方法中的字段值应该是全零或全一,但不能两者兼而有之。请帮忙。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    如果您希望查询仅返回年龄,则投影必须仅包含您想要的字段。不是你不想要的:

    db.projection.find({}, {_id:0, age:1})
    

    _id 的例外,您可以指定不包含它。

    结果

    {
      "age": 22
    }
    

    来自documentation

    投影不能同时包含包含和排除规范,除了 _id 字段的排除。在显式包含字段的投影中,_id 字段是唯一可以显式排除的字段。

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 2017-12-07
      • 2012-02-10
      • 2014-02-28
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多