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.
[code language=”javascript”]
{
id: 1,
name: "Ken",
email: "ken@gmail.com",
age:"30",
profession:"programmer",
interests: ["reading", "video game", "travel"]
}
[/code]
Insert a new document
[code language=”javascript”]
db.users.insert(
{
id: 2,
name: "Amy",
email: "amy@gmail.com",
age:"22",
profession:"writer",
interests: ["writing", "watch tv", "travel"]
}
);
[/code]
Get the total number of documents in the users collection.
[code language=”javascript”]
db.users.count();
[/code]
Read a document where the name is Amy and email is amy@gmail.com
[code language=”javascript”]
db.users.find({‘name’:’Amy’, ’email’:’amy@gmail.com’});
[/code]
Read documents where profession is programmer
[code language=”javascript”]
db.users.find({‘profession’:’programmer’});
[/code]
Read documents where interests has travel using the $in clause
[code language=”javascript”]
db.users.find({‘interests’:{"$in":[‘travel’]}});
[/code]
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
[code language=”javascript”]
db.users.find({‘age’:{‘$gt’: 25}});
[/code]
Search within Codexpedia

Search the entire web
