使用find()方法在投影中出错

ks2*_*lik 3 mongodb mongodb-query

我是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 }
Run Code Online (Sandbox Code Playgroud)

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

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 }
Run Code Online (Sandbox Code Playgroud)

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") }
Run Code Online (Sandbox Code Playgroud)

工作得很好,但是

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

错误:错误:{"$ err":"无法规范化查询:BadValue Projection不能混合使用包含和排除.","code":17287}

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

Con*_*uay 6

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

db.projection.find({}, {_id:0, age:1})
Run Code Online (Sandbox Code Playgroud)

_id的例外情况,您可以指定不包含它.

结果

{
  "age": 22
}
Run Code Online (Sandbox Code Playgroud)

文档:

除了排除_id字段外,投影不能同时包含include和exclude规范.在明确包含字段的投影中,_id字段是您可以显式排除的唯一字段.