我是MongoDB的新手。当我在芒果尝试基本的东西时,遇到了一个问题。我找了一下,但没有找到满意的答案。
我有一个非常简单的集合,名为“用户”,有一些人的名字和年龄。下面是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投影不能包含和排除。“,”代码“:17287 }
正在失败并出现错误,如上文所示。如果投影中存在冲突的条件,我搜索了这个问题,但是我不认为在我的方法调用中有类似的情况。在find方法中,是否有类似于字段值的规则要么全部为零,要么全部为零,但不能两者兼而有之。请帮帮忙。
发布于 2015-12-11 13:44:27
如果希望查询只返回年龄,则投影必须只包含希望拥有的字段。不是你不想要的那个:
db.projection.find({}, {_id:0, age:1})对于_id,您可以指定不包含它。
结果
{
"age": 22
}来自文档
除了排除_id字段之外,投影不能同时包含和排除规范。在显式包含字段的投影中,_id字段是唯一可以显式排除的字段。
https://stackoverflow.com/questions/34224799
复制相似问题