1

I have a collection looking somewhat like this:

{
  "colors": ["blue","white"],
  "items": {
    "old": {
      "name": "test"
    }
    "current": {
      "name": "new_test"
    }
  }
},
{
  "colors": ["red","green"],
  "items": {
    "old": {
      "name": "test2"
    }
    "current": {
      "name": "new_test2"
    }
  }
},

Is it possible to use find like this:

db.collection.find({"items": { "old": { "name": "test" } } })

So the command would return:

{
  "colors": ["blue","white"],
  "items": {
    "old": {
      "name": "test"
    }
    "current": {
      "name": "new_test"
    }
  }
}

Is this possible?

Emil Hemdal
  • 589
  • 2
  • 8
  • 27

1 Answers1

4

Yes, you can use the 'dot notation' to reach into the object:

db.collection.find({"items.old.name": "test" })

The query syntax you used also works, but it has different semantics: It will match the entire subdocument for equality instead of just a single field. For instance, the following query would also return a result:

db.foo.find({"items.old": {"name" : "test"} }),

butdb.collection.find({"items": { "old": { "name": "test" } } }) does not, because items also contains a current field.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82