MongoDB:无法规范化查询:BadValue 投影不能混合包含和排除



我是MongoDB与CakePHP较新的。

当我编写以下查询时,它将执行得非常好。

db.testData.find()
{
    "_id" : ObjectId("53d1f79db8173a625961ff3d"),
    "name" : "sadikhasan",
    "created" : ISODate("2014-07-25T06:22:21.701Z")
}

当我运行以下查询只获取name时,它返回一个错误:

db.testData.find({},{name:1, created:0})
error: {
    "$err" : "Can't canonicalize query: BadValue Projection cannot 
              have a mix of inclusion and exclusion.",
    "code" : 17287
}

当我运行以下查询只获得name_id:0时,它执行得很好:

db.testData.find({},{name:1, _id:0})
{ "name" : "sadikhasan" }

我的问题是,为什么我得到一个错误,当我写created:0在投影列表。

不能混合包含和排除,唯一的例外是_id字段。

例如:

{
   "_id": ObjectId("53d1fd30bdcf7d52c0d217de"),
   "name": "bill",
   "birthdate": ISODate("2014-07-80T00:00:00.000Z"),
   "created": ISODate("2014-07-25T06:44:38.641Z")
}

如果你只想要"姓名"one_answers"出生日期",你需要这样做:

db.collection.find({},{ "_id": 0, "name": 1, "birthdate": 1 })

或:

db.collection.find({},{ "_id": 0, "created": 0 })

但不允许"混合"除"_id"以外的任何其他操作

db.collection.find({},{ "_id": 0, "name": 1, "created": 0 })

也会产生错误。

抛出错误"Can't规范化查询:BadValue Projection不能混合包含和排除",因为您混合了包含和排除。1代表包容,0代表排除。您可以在查询中使用0或1。因此,如果你希望只看到_id和name字段,use可以使用:1)包含:

              db.testdata.find({}, {_id:1,name:1})
2)排除:
              db.testdata.find({},{created:0})

在上述两个场景中,它将只显示_id和name字段。

我遇到了同样的问题。这意味着你不能告诉MongoDB选择一个特定的字段,同时取消选择另一个字段。

这是错误的,不能在选择选项中这样指定错误:-投影不能混合包含和排除。

reviewSchema.pre(/^find/, function (next) {
    this.populate({
        path: 'tour',
        select: 'name -__v'
    })
    next();
});

正确的格式。

reviewSchema.pre(/^find/, function (next) {
    this.populate({
        path: 'tour',
        select: 'name' // Removed -__v
    })
    next();
});

用简单的话来描述解决方案,您可以告诉MongoDB您想要或不想要MongoDB的所有字段。

意味着在select方法中您必须只提到必需或非必需字段。像下面的

find({<!--query here--!>}).select({
        password: 0,
        allowed_ip: 0,
        username: 0,
        password: 0,
        __v: 0,
        _id: 0
    });

应该是0(排除/不需要)或1(包含/必填字段)干杯!!

最新更新