2. Start the Shell
• C:mongodb-win32-x86_64-
2.2.3bin>mongo.exe
MongoDB shell version: 2.2.3
connecting to: test
3. Create Document the insert()
> register={"uName":"anish",
... "date":new Date()}
{ "uName" : "anish", "date" : ISODate("2013-03-10T10:08:30.891Z") }
> db.user.insert(register)
> db.user.find()
{ "_id" : ObjectId("513c581f1b37fce6f69eb9e0"), "fname" :
"anish", "date" : ISODate("2013-03-10T09:52:53.144Z") }
{ "_id" : ObjectId("513c5be21b37fce6f69eb9e2"), "uName" :
"anish", "date" : ISODate("2013-03-10T10:08:30.891Z") }
The “_id” field If you attempt to insert a document without
the _id field, the client library or the mongod instance will add
an _id field and populate the field with a unique ObjectId.
7. Reading/finding in Document
Syntax
db.collection.find( <query>,
<projection> )
<query> argument corresponds to
the WHERE statement, and
<projection> argument corresponds
to the list of fields to select from the
result set.
8. Reading Document
> db.user.findOne()
{
"_id" : ObjectId("513c581f1b37fce6f69eb9e0"),
"fname" : "anish",
"date" : ISODate("2013-03-10T09:52:53.144Z")
}
> db.user.find()
{ "_id" : ObjectId("513c581f1b37fce6f69eb9e0"), "fname"
: "anish", "date" : ISODate("2013-03-10T09:52:53.144Z") }
{ "_id" : ObjectId("513c5be21b37fce6f69eb9e2"),
"uName" : "anish", "date" : ISODate("2013-03-
10T10:08:30.891Z") }
Refer more use case on find() on the Other video
9. findOne()
Find the first record in the document
> db.user.findOne()
{
"_id" : ObjectId("513c6ef1cfce9090d3fd8b1d"),
"date" : ISODate("2013-03-10T11:30:50.555Z"),
"remarks" : [
{
"name" : "anish",
"rate" : "good"
},
{
"name" : "nath",
"rate" : "bad"
}
],
"uName" : "anish"
}
10. findOne() : specify which key to return
• Find the first record in the document and return only “_id”
> db.user.findOne({},{"_id":1})
{ "_id" : ObjectId("513c6ef1cfce9090d3fd8b1d") }
• Find the first record in the document and return only
“_id” and date
> db.user.findOne({},{"_id":1,"date":1})
{
"_id" : ObjectId("513c6ef1cfce9090d3fd8b1d"),
"date" : ISODate("2013-03-10T11:30:50.555Z")
}
• Find the first record in the document and return all the
data except the “_id” field
> db.user.findOne({},{"_id":0})
{
"date" : ISODate("2013-03-10T11:30:50.555Z"),
"remarks" : [
{
"name" : "anish",
"rate" : "good"
},
{
"name" : "nath",
"rate" : "bad"
}
],
"uName" : "anish"
}