Database Reference
In-Depth Information
will be unique among all _id values in the collection, which is the only hard require-
ment for the field.
I'll have more to say about object ID s in the next chapter. Let's continue for now by
adding a second user to the collection:
> db.users.save({username: "jones"})
There should now be two documents in the collection. Go ahead and verify this by
running the count command:
> db.users.count()
2
Now that you have more than one document in the collection, we can look at some
slightly more sophisticated queries. Like before, you can still query for all the docu-
ments in the collection:
> db.users.find()
{ _id : ObjectId("4bf9bec50e32f82523389314"), username : "smith" }
{ _id : ObjectId("4bf9bec90e32f82523389315"), username : "jones" }
But you can also pass a simple query selector to the find method. A query selector is a
document that's used to match against all documents in the collection. To query for
all documents where the username is jones , you pass a simple document that acts as
your query selector like so:
> db.users.find({username: "jones"})
{ _id : ObjectId("4bf9bec90e32f82523389315"), username : "jones" }
The query selector {username: "jones"} returns all documents where the username
is jones —it literally matches against the existing documents.
I've just presented the basics of creating and reading data. Now it's time to look at
how to update that data.
2.1.3
Updating documents
All updates require at least two arguments. The first specifies which documents to
update, and the second defines how the selected documents should be modified.
There are two styles of modification; in this section we're going to focus on targeted
modifications , which are most representative of MongoDB's distinct features.
To take an example, suppose that user smith decides to add her country of resi-
dence. You can record this with the following update:
> db.users.update({username: "smith"}, {$set: {country: "Canada"}})
This update tells MongoDB to find a document where the username is smith , and
then to set the value of the country property to Canada . If you now issue a query,
you'll see that the document has been updated accordingly:
> db.users.find({username: "smith"})
{ "_id" : ObjectId("4bf9ec440e32f82523389316"),
"country" : "Canada", username : "smith" }
Search WWH ::




Custom Search