B
B
beduin012015-07-12 12:01:05
NoSQL
beduin01, 2015-07-12 12:01:05

MongoDB select from nested array?

Simple question, I can't figure it out. Square brackets are in our Mongo array right?
How can I find the contents of tags (and a specific value in it) using find

db.qtest.insert(
{
date: Date("2013-01-14"),
name: "Roma",
tags: [{Python:14,Ruby:10,C:4}]
}
)

If I clarify. I'm trying to figure out how to do a find on a nested array.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lega, 2015-07-12
@lega

Don't try to make tricky queries (which are often slow), it's often better to make the structure of the document where data can be retrieved quickly and easily.
For example, for your task, you can do this:

> db.qtest.insert({
  date: Date("2013-01-14"),
  name: "Roma",
  tags:['python', 'ruby', 'c'],
  counts: {python: 14, ruby:10, c:4 }
})

Search:
> db.qtest.find({tags: 'python'}, {date: 1, name:1, 'counts.python':1}).pretty()
{
  "_id" : ObjectId("55a28f4624db1e49cecbc89f"),
  "date" : "Sun Jul 12 2015 21:01:10 GMT+0500 (YEKT)",
  "name" : "Roma",
  "counts" : {
    "python" : 14
  }
}

Then you can make an index on tags db.qtest.ensureIndex({tags: 1}), and this query will work quickly when the collection is large.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question