MongoDB – $exists and $regex operator

$exists

As mongoDB is  schema less. In database some table can have different schema. for example if we have Persons database and

in that database we have people collection.  If we need to know that whether a certain field exists in collection or not.

Syntax: { field: { $exists: <boolean> } }

 

db.people.find( { profession: { $exists: true} } )

This query will return results with out profession field.

$regex

If we want to use regular expression in our queries then mongoDB has $regex operator.  $regex uses PCRE engine.

Suppose we have users collection, To find users with having m in their name field, then we can use following query

> db.users.find({"name": {$regex :"m"}});

or

> db.users.find({"name": /m/})

 

 

 

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.