Databases Reference
In-Depth Information
“zip” : 10001 }
{ “_id” : ObjectId(“4c97a6555c760000000054d8”), “name” : “Don Joe”,
“zip” : 10001 }
To get a list of all those who have the name “John Doe,” you could query like so:
> db.location.find({name: “John Doe”});
{ “_id” : ObjectId(“4c97053abe67000000003857”), “name” : “John Doe”,
“zip” : 10001 }
{ “_id” : ObjectId(“4c97a7ef5c760000000054da”), “name” : “John Doe”,
“zip” : 94129 }
In both these queries that fi lter the collection, a query document is passed as a parameter to the
find method. The query document specifi es the pattern of keys and values that need to be matched.
MongoDB supports many advanced querying mechanisms beyond simple fi lters, including pattern
representation with the help of regular expressions.
Because a database includes newer data sets, it is possible the structure of the collection will become
a constraint and thus need modifi cation. In traditional relational database sense, you may need
to alter the table schema. In relational databases, altering table schemas also means taking on a
complicated data migration task to make sure data in the old and the new schema exist together.
In MongoDB, modifying a collection structure is trivial. More accurately, collections, analogous
to tables, are schema-less and so it allows you to store disparate document types within the same
collection.
Consider an example where you need to store the location preferences of another user, whose name
and zip code are identical to a document already existing in your database, say, another {name:
“Lee Chang”, zip: 94129} . Intentionally and not realistically, of course, the assumption was that
a name and zip pair would be unique!
To distinctly identify the second Lee Chang from the one in the database, an additional attribute,
the street address, is added like so:
> anotherLee = {name:”Lee Chang”, zip: 94129, streetAddress:”37000 Graham Street”};
{
“name” : “Lee Chang”,
“zip” : 94129,
“streetAddress” : “37000 Graham Street”
}
> db.location.save(anotherLee);
Now getting all documents, using find , returns the following data sets:
> db.location.find();
{ “_id” : ObjectId(“4c97053abe67000000003857”), “name” : “John Doe”,
“zip” : 10001 }
{ “_id” : ObjectId(“4c970541be67000000003858”), “name” : “Lee Chang”,
“zip” : 94129 }
{ “_id” : ObjectId(“4c970548be67000000003859”), “name” : “Jenny Gonzalez”,
“zip” : 33101 }
Search WWH ::




Custom Search