MongoDB: Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion

Sadikhasan picture Sadikhasan · Jul 25, 2014 · Viewed 39.4k times · Source

I am newer in MongoDB with CakePHP.

When I write the following query it will execute very well.

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

When I run the following query to get only name, it returns an error:

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
}

When I run the following query to get only name with _id:0, then it executes well:

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

My question is, why I am getting an error when I write created:0 in the projection list. Thanks for help in advance.

Answer

Neil Lunn picture Neil Lunn · Jul 25, 2014

You cannot mix inclusion and exclusion, the only exception is the _id field.

For example if you have this:

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

If all you want is the "name" and "birthdate" you need to do this:

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

Or this:

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

But it is not allowed to "mix" any other operations other than "_id"

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

That would also produce an error.

This is all covered in the manual pages.