When you use methods such as find()
or findOne()
in MongoDB, by default you get the whole document returned. And if you use projections, you can return specific key/value pairs.
But what if you only want the value?
You can extract the value of a field by appending that field’s name to your query when using findOne()
.
Example
Suppose we have a collection called products
with the following documents:
{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L" ] } { "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL" ] } { "_id" : 3, "product" : "Cap", "sizes" : [ "M", "L" ] }
If we wanted to return the first document’s product, we could do the following:
db.products.findOne().product
Result:
Bat
Note that we used the findOne()
method. This technique doesn’t work on the find()
method. The findOne()
method returns a single document, whereas the find()
method merely returns a cursor to the document.
If we wanted to return the array we could do this:
db.products.findOne().sizes
Result:
[ "S", "M", "L" ]
And we can get an array value by referencing its index:
db.products.findOne().sizes[0]
Result:
S
Arrays are zero-based, and so 0
references the first element in the array, 1
references the second element, 2
the third, and so on.
Specific Document
By default, the findOne()
method returns the first document in the collection. We can select a different document by specifying passing a query as the first argument.
I say “first argument” because findOne()
also accepts a projection
argument as an optional second argument.
db.products.findOne({_id: 2}, {sizes: 1, _id: 0}).sizes
Result:
[ "S", "L", "XL" ]
In this case I added a projection argument, but it had no effect on the result. But it would have had an effect if I’d specified a value of 0. That would have resulted in nothing being returned.
Embedded Documents
You can use dot notation to return values from embedded documents
Example document:
{ "_id" : 1, "name" : "Wag", "details" : { "type" : "Dog", "weight" : 20 } }
We could do the following to return a value from the embedded document:
db.pets.findOne().details.type
Result:
Dog