1
> db.checklistDB.find({},{title:1, _id:0})
{ "title" : "Untitled Checklist" }
{  }
{  }
{  }
{  }
{  }
> db.checklistDB.find({},{title:1})
{ "title" : "Untitled Checklist", "_id" : "4FaJcAkzAY3Geyggm" }
{ "_id" : "3imNYy8SPcRDjLcqz" }
{ "_id" : "977fPtvEn7hiStqzp" }
{ "_id" : "QcAEMnr6R7qfaWFR8" }
{ "_id" : "eEsmKMdQGYKqnhTNB" }
{ "_id" : "cL6R8qxwWhvTr2kmy" }

Hi Guys,

As you can see from the above, I rand 2 commands:

db.checklistDB.find( {} , { title : 1 } ) and *db.checklistDB.find( {} , { title : 1 , _id : 0} )

Both queries returns 6 records which is all the records that exists in the database. I would imagine that it will only return records that have "title" as a field. Is there something I'm doing wrong?

4

1 回答 1

3

Second argument for find is projection. In your case it looks for title field inside document, and if it doesn’t exist returns none. If you want to filter documents you should use query like this:

 db.checklistDB.find({title: {$exists: true}}, {title:1, _id:0})

EDIT If you take your query:

db.checklistDB.find({}, {title:1, _id:0})

It translates to: retrieve all documents ({} as query argument) and for every document give me title if exist or default value (none) if it doesn’t ({title:1, _id:0} as projection argument). Projection argument is used only to transform not to filter documents.

于 2013-10-03T13:18:55.040 回答