MongoDB – Interactive shell searching records

  • Find all collections

>db.comments.find()
{ “_id” : ObjectId(“4c6580f4fb4d000000002a71”), “author” : “tom”, “date” : “Fri Aug 13 2010 13:29:09 GMT-0400 (Eastern Daylight Time)” }
{ “_id” : ObjectId(“4c658418fb4d000000002a72”), “author” : “Tom”, “date” : “Fri Aug 13 2010 13:42:34 GMT-0400 (Eastern Daylight Time)”, “text” : “MongoDB is cool” }

  • Find a record using criteria

> db.posts.find( {author:”Tom”})
{ “_id” : ObjectId(“4c658418fb4d000000002a72”), “author” : “Tom”, “date” : “Fri Aug 13 2010 13:42:34 GMT-0400 (Eastern Daylight Time)”, “text” : “MongoDB is cool” }

  • Searching using wildcards

> db.posts.find({text:/ongo/})
{ “_id” : ObjectId(“4c658418fb4d000000002a72”), “author” : “Tom”, “date” : “Fri Aug 13 2010 13:42:34 GMT-0400 (Eastern Daylight Time)”, “text” : “MongoDB is cool” }

  • Counting the number of results

> db.posts.find({text:/ongo/}).count()
1

  • Search using criteria containing operators $lt, $gt, $lte, $gte, $in, $nin

> db.posts.find({date: {$lt: new Date()}})
{ “_id” : ObjectId(“4c6580f4fb4d000000002a71”), “author” : “mike”, “date” : “Fri Aug 13 2010 13:29:09 GMT-0400 (Eastern Daylight Time)” }
{ “_id” : ObjectId(“4c658418fb4d000000002a72”), “author” : “Tom”, “date” : “Fri Aug 13 2010 13:42:34 GMT-0400 (Eastern Daylight Time)”, “text” : “MongoDB is cool” }

  • Find returns cursor and not record collections. Use iterate to find specific records.

> var cur=db.comments.find()
>
> cur.hasNext()
true
> cur.forEach(
… function (item) {
… print( tojson(item))
… });

{
“_id” : ObjectId(“4c6595a4c706000000004ead”),
“author” : “Tommy”,
“date” : “Fri Aug 13 2010 14:57:10 GMT-0400 (Eastern Daylight Time)”,
“text” : “MongoDB is cool”
}
{
“_id” : ObjectId(“4c65963b8140000000004e83”),
“author” : “mark”,
“date” : “Fri Aug 13 2010 15:00:08 GMT-0400 (Eastern Daylight Time)”,
“text” : “MongoDB!!”
}
>

MongoDB – Installation and First Steps

MongoDb Interactive shell – basic commands

MongoDb Interactive shell – searching records

dbShell Quick Reference

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: