Find in subdocuments returning document

有些话、适合烂在心里 提交于 2020-01-03 02:28:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19605677/find-in-subdocuments-returning-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!