If you don’t have it running already, go ahead and start the mongod server as well as a mongo shell. The shell runs JavaScript. There are some global commands you can execute, like help or exit. Commands that you execute against the current database are executed against the db object, such as db.help() or db.stats(). Commands that you execute against a specific collection are executed against the db.COLLECTION_NAME object, such as db.unicorns.help() or db.unicorns.count().
Go ahead and enter db.help(), you’ll get a list of commands that you can execute against the db object.
Create
First we’ll use the global use helper to switch databases, so go ahead and enter use learn. It doesn’t matter that the database doesn’t really exist yet. The first collection that we create will also create the actual learn database.
> use learn
switched to db learn
>
Now that you are inside a database, you can start issuing database commands, like db.getCollectionNames(). If you do so, you should get an empty array ([ ]).
> db.getCollectionNames()
[ ]
>
Since collections are schema-less, we don’t explicitly need to create them. We can simply insert a document into a new collection. To do so, use the insert command, supplying it with the document to insert:
> db.unicorns.insert({name:'Aurora',gender:'f',weight:150})
WriteResult({ "nInserted" : 1 })
>
The above line is executing insert against the unicorns collection, passing it a single parameter. Internally MongoDB uses a binary serialized JSON format called BSON. Externally, this means that we use JSON a lot, as is the case with our parameters. If we execute db.getCollectionNames() now, we’ll actually see two collections: unicorns and system.indexes. The collection system.indexes is created once per database and contains the information on our database’s indexes.
Read
You can now use the find command against unicorns to return a list of documents:
> db.unicorns.find()
{ "_id" : ObjectId("56bf2f3910a4febbd2830cfa"), "name" : "Aurora", "gender" : "f", "weight" : 150 }
Use pretty function along with find() to get more clearer well structured representation of inserted data.
> db.unicorns.find().pretty()
{
"_id" : ObjectId("56bf2f3910a4febbd2830cfa"),
"name" : "Aurora",
"gender" : "f",
"weight" : 150
}
Notice that, in addition to the data you specified, there’s an _id field. Every document must have a unique _id field. You can either generate one yourself or let MongoDB generate a value for you which has the type ObjectId. Most of the time you’ll probably want to let MongoDB generate it for you. By default, the _id field is indexed - which explains why the system.indexes collection was created. You can look at system.indexes:
> db.system.indexes.find()
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "learn.unicorns" }
What you’re seeing is the name of the index, the database and collection it was created against and the fields included in the index.
>db.unicorns.insert({name:'Leto',gender:'m', home:'Arrakeen',worm:false})
WriteResult({ "nInserted" : 1 })
>
And, again use find to list the documents. Once we know a bit more, we’ll discuss this interesting behavior of MongoDB, but hopefully you are starting to understand why the more traditional terminology wasn’t a good fit.
> db.unicorns.find().pretty()
{
"_id" : ObjectId("56bf2f3910a4febbd2830cfa"),
"name" : "Aurora",
"gender" : "f",
"weight" : 150
}
{
"_id" : ObjectId("56bf35a410a4febbd2830cfb"),
"name" : "Leto",
"gender" : "m",
"home" : "Arrakeen",
"worm" : false
}
Delete
Before delving too deeply into selectors, let’s set up some data to play with. First, remove what we’ve put so far in the unicorns collection via: db.unicorns.remove({}).
> db.unicorns.remove({})
WriteResult({ "nRemoved" : 2 })
> db.unicorns.find().pretty()
>
If you want to delete a particular record:
> db.unicorns.remove({name:'Himanshu'})
WriteResult({ "nRemoved" : 1 })
>
Mastering Selectors
In addition to the six concepts we’ve explored, there’s one practical aspect of MongoDB you need to have a good grasp of before moving to more advanced topics: query selectors. A MongoDB query selector is like the where clause of an SQL statement. As such, you use it when finding, counting, updating and removing documents from collections. A selector is a JSON object, the simplest of which is {} which matches all documents. If we wanted to find all female unicorns, we could use {gender:'f'}.
Once all data has been removed from collection unicorns, issue the following inserts to get some data we can play with (I suggest you copy and paste this):
db.unicorns.insert({name: 'Horny',dob: new Date(1992,2,13,7,47),
loves: ['carrot','papaya'], weight: 600,gender: 'm',vampires: 63});
db.unicorns.insert({name: 'Aurora', dob: new Date(1991, 0, 24, 13, 0),
loves: ['carrot', 'grape'], weight: 450, gender: 'f', vampires: 43});
db.unicorns.insert({name: 'Unicrom', dob: new Date(1973, 1, 9, 22, 10),
loves: ['energon', 'redbull'], weight: 984, gender: 'm', vampires: 182});
db.unicorns.insert({name: 'Roooooodles', dob: new Date(1979, 7, 18, 18, 44),
loves: ['apple'], weight: 575, gender: 'm', vampires: 99});
db.unicorns.insert({name: 'Solnara', dob: new Date(1985, 6, 4, 2, 1),
loves:['apple', 'carrot', 'chocolate'], weight:550, gender:'f', vampires:80});
db.unicorns.insert({name:'Ayna', dob: new Date(1998, 2, 7, 8, 30),
loves: ['strawberry', 'lemon'], weight: 733, gender: 'f', vampires: 40});
db.unicorns.insert({name:'Kenny', dob: new Date(1997, 6, 1, 10, 42),
loves: ['grape', 'lemon'], weight: 690, gender: 'm', vampires: 39});
db.unicorns.insert({name: 'Raleigh', dob: new Date(2005, 4, 3, 0, 57),
loves: ['apple', 'sugar'], weight: 421, gender: 'm', vampires: 2});
db.unicorns.insert({name: 'Leia', dob: new Date(2001, 9, 8, 14, 53),
loves: ['apple', 'watermelon'], weight: 601, gender: 'f', vampires: 33});
db.unicorns.insert({name: 'Pilot', dob: new Date(1997, 2, 1, 5, 3),
loves: ['apple', 'watermelon'], weight: 650, gender: 'm', vampires: 54});
db.unicorns.insert({name: 'Nimue', dob: new Date(1999, 11, 20, 16, 15),
loves: ['grape', 'carrot'], weight: 540, gender: 'f'});
db.unicorns.insert({name: 'Dunx', dob: new Date(1976, 6, 18, 18, 18),
loves: ['grape', 'watermelon'], weight: 704, gender: 'm', vampires: 165});
Now that we have data, we can master selectors. {field: value} is used to find any documents where field is equal to value. {field1: value1, field2: value2} is how we do an and statement. The special $lt, $lte, $gt, $gte and $ne are used for less than, less than or equal, greater than, greater than or equal and not equal operations. For example, to get all male unicorns that weigh more than 700 pounds, we could do:
db.unicorns.find({gender: 'm',weight: {$gt: 700}})
//or (not quite the same thing, but for demonstration purposes)
db.unicorns.find({gender: {$ne: 'f'},weight: {$gte: 701}})
The $exists operator is used for matching the presence or absence of a field, for example the following command should return a single document.
> db.unicorns.find({vampires:{$exists:false}}).pretty()
{
"_id" : ObjectId("56bf378810a4febbd2830d06"),
"name" : "Nimue",
"dob" : ISODate("1999-12-20T10:45:00Z"),
"loves" : [
"grape",
"carrot"
],
"weight" : 540,
"gender" : "f"
}
The ‘$in’ operator is used for matching one of several values that we pass as an array, for example:
db.unicorns.find({loves: {$in:['apple','orange']}})
This returns any unicorn who loves ‘apple’ or ‘orange’.
If we want to OR rather than AND several conditions on different fields, we use the $or operator and assign to it an array of selectors we want or’d:
db.unicorns.find({gender: 'f',
$or: [{loves: 'apple'},
{weight: {$lt: 500}}]})
The above will return all female unicorns which either love apples or weigh less than 500 pounds.
There’s something pretty neat going on in our last two examples. You might have already noticed, but the loves field is an array. MongoDB supports arrays as first class objects. This is an incredibly handy feature. Once you start using it, you wonder how you ever lived without it. What’s more interesting is how easy selecting based on an array value is: {loves: 'watermelon'} will return any document where watermelon is a value of loves.
What we’ve covered so far though is the basics you’ll need to get started. It’s also what you’ll
end up using most of the time. We’ve seen how these selectors can be used with the find command. They can also be used with the remove command which we’ve briefly looked at, the count command, which we haven’t looked at but you can probably figure out, and
the update command which we’ll spend more time with later on.
The ObjectId which MongoDB generated for our _id field can be selected like so:
db.unicorns.find({_id: ObjectId("TheObjectId")})
> db.unicorns.find( {_id: ObjectId("56bf378810a4febbd2830d01")}).pretty()
{
"_id" : ObjectId("56bf378810a4febbd2830d01"),
"name" : "Ayna",
"dob" : ISODate("1998-03-07T03:00:00Z"),
"loves" : [
"strawberry",
"lemon"
],
"weight" : 733,
"gender" : "f",
"vampires" : 40
}
We will explore find() in more detail in future posts.
We will explore find() in more detail in future posts.
No comments:
Post a Comment