Getting Data with Queries
Learn how to query and filter MongoDB collections.
Embedded document
A document is like a row of data. It consists of a key-value pair of the data. An embedded document is a document with a value that’s a field in another document.
{
"name" : "John Doe"
"age" : 24,
"education" : {
"primary": "St Lukes",
"secondary": "Federal Govt College",
"tertiary" : "University of Ilorin"
}
}
The education field of the top document (object) above is an embedded document. Dot notation is used when querying for an embedded document.
What’s a query?
A query in MongoDB is the way data is retrieved from the database. A query statement could be used to retrieve all data in a collection, or it can contain criteria that restricts the retrieved data.
Query structure in MongoDB
A query in MongoDB usually takes the form of the following:
db.collectionName.find()
Or:
db.collectionName.findOne()
Meteor MongoDB API for querying MongoDB is slightly different because it takes this form:
Mongo.Collection.find()
//or
Mongo.Collection.findOne()
Meteor MongoAPI find
returns a reactive cursor that reruns when dependencies change, while findOne
returns a single document. To pull data out of a cursor, we append the fetch()
method at the end.
Mongo.Collection.find().fetch()
//or
Mongo.Collection.findOne()
The difference between how we query for data in Meteor API and MongoDB is the chaining of the fetch()
method used to pull data from a cursor.
Mongo.Collection.findOne(selectors, options)
The code above finds the first document that matches a selector.
Common MongoDB query operators
Get hands-on with 1400+ tech skills courses.