gpt4 book ai didi

mongodb - 使用 find() 方法进行投影时出错

转载 作者:可可西里 更新时间:2023-11-01 09:24:22 25 4
gpt4 key购买 nike

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

我有一个名为“users”的非常简单的集合,其中包含一些人的姓名和年龄。以下是 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})

Error: error: { "$err" : "Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.", "code" : 17287 }

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

最佳答案

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

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

_id 异常,可以指定不包含。

结果

{
"age": 22
}

来自documentation :

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.

关于mongodb - 使用 find() 方法进行投影时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34224799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com