mongodb quick references for finding documents

Assume there is a collection called users and each user is represented in a document like this. The following query examples are all querying against this user collection.

{
	id: 1,
	name: "Ken",
	email: "ken@gmail.com",
	age:"30",
	profession:"programmer",
	interests: ["reading", "video game", "travel"]
}

Insert a new document

db.users.insert(
{
	id: 2,
	name: "Amy",
	email: "amy@gmail.com",
	age:"22",
	profession:"writer",
	interests: ["writing", "watch tv", "travel"]
}
);

Get the total number of documents in the users collection.

db.users.count();

Read a document where the name is Amy and email is amy@gmail.com

db.users.find({'name':'Amy', 'email':'amy@gmail.com'});

Read documents where profession is programmer

db.users.find({'profession':'programmer'});

Read documents where interests has travel using the $in clause

db.users.find({'interests':{"$in":['travel']}});

Read documents where age is greater than 25. Notice the comparison operator $gt used in this query. Here are other comparison operators available in mongodb: $lt, $gte and $lte

db.users.find({'age':{'$gt': 25}});

Search within Codexpedia

Custom Search

Search the entire web

Custom Search