I
I
ivanesi2014-10-31 13:15:47
MongoDB
ivanesi, 2014-10-31 13:15:47

How to get part of a document in mongo?

For example, there is such a document in the authors collection:

{
  "name" : "Andrew Erlichson",
  "books" :  {
                [
                  {
                    "title" : "MongoDb best practice",
                    "name" : "o'Reilly",
                    "year" : "2013"
                  }
                 ]
               }
 }

How to get only the zero element of the books array? how to get the value of the year field?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
ivanesi, 2014-11-01
@ivanesi

Found the answer in the video tutorial. Everything is solved easier:
well, or

db.authors.findOne( { name : "Andrew Erlichson" } ).books[0].year

A
anyd3v, 2014-10-31
@anyd3v

what does null mean? first?
docs.mongodb.org/manual/reference/method/cursor.limit
"how to pull the year field value?"
docs.mongodb.org/manual/reference/method/db.collec...
Have you even read the documentation?

L
lega, 2014-11-01
@lega

How to get only the zero element of the books array?

Part of an array (or one element) can be accessed using $slice
db.col.find({}, {'books.year': 1}) - so it should return the year field (but over all array elements).
If you don't really need an array, then you can use a dictionary instead with keys 0, 1, 2, 3...
Then the query will be like this: db.col.find({}, {'books.0.year' : one})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question