Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Search by property name for any Document with that property

Tags:

mongodb

How do I do a search in MongoDB that searches for any documents with a given property?

What I want to do is find all the documents that have the property regardless of it's value and I don't seem to be able to do this. I've tried the following

db.collection.find({"property", null}); //Finds things that don't have that property
db.collection.find({"proprety", {}}); //Doesn't find anything unless something has the empty object as the value

Is there actually a syntax for this or would I need to do a mapreduce operation?

like image 727
RobV Avatar asked Oct 04 '10 16:10

RobV


2 Answers

Here's the sample answer using $exists:

db.collection.find( { property : { $exists: true } } );
like image 166
vladimir Avatar answered Oct 07 '22 13:10

vladimir


Just invert the query and search for documents where the property is not null ($ne not equals)

db.collection.find( { property : { $ne : null } } );
like image 20
halfdan Avatar answered Oct 07 '22 13:10

halfdan