Wednesday, August 20, 2014

Querying

Introduction to find

find method is used to perform queries in MongoDB
Querying returns a subset of documents in a collection.

db.c.find() is same as db.c.find({})
   which matches every document in the collection
Eg:
db.users.find({"age" : 27})
db.users.find({"username" : "joe"})

and operator
db.users.find({"username" : "joe", "age" : 27})   , acts as an "and" operator

Specifying which Keys to and not to return

> db.users.find({}, {"username" : 1, "email" : 1})
{
     "_id" : ObjectId("4ba0f0dfd22aa494fd523620"),
     "username" : "joe",
     "email" : "joe@example.com"
}  

Avoid printing _id
> db.users.find({}, {"fatal_weakness" : 0})

> db.users.find({}, {"username" : 1, "_id" : 0})
{
     "username" : "joe",
}

Limitations

The value of a query document must be a constant as far as the database is concerned.
That is, it cannot refer to the value of another key in the document.

Query Criteria

"$lt", "$lte", "$gt", and "$gte" are all comparison operators

Eg:
> db.users.find({"age" : {"$gte" : 18, "$lte" : 30}})

> start = new Date("01/01/2007")
> db.users.find({"registered" : {"$lt" : start}})

> db.users.find({"username" : {"$ne" : "joe"}})

OR Queries

> db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})

Allows you to specify criteria of different types
> db.users.find({"user_id" : {"$in" : [12345, "joe"]})

> db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})

to find documents where "ticket_no" is 725 or "winner" is true
> db.raffle.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})

"$or" can contain other conditionals
> db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725, 542, 390]}},
{"winner" : true}]})

$not

It can be applied on top of any other criteria

"$mod" queries for keys whose values, when divided by the first value given, have a remainder of the second value

> db.users.find({"id_num" : {"$mod" : [5, 1]}})

> db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})

Type-Specific Queries

> db.c.find({"y" : null})
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }

null not only matches itself but also matches “does not exist

> db.c.find({"z" : null})
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523622"), "y" : 1 }
{ "_id" : ObjectId("4ba0f148d22aa494fd523623"), "y" : 2 }




No comments:

Post a Comment