在子文档中查找返回文档

在子文档中查找返回文档

本文介绍了在子文档中查找返回文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  {
colors:[blue,
old:{
name:test
}
current:{
name:new_test
}
}
},
{
colors:[red,green],
$b:{
old:{
name:test2
}
current:{
name new_test2

}
},

使用这样的查找:

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

所以命令会返回:

  {
colors:[blue,white],
items:{
旧的:{
name:test
}
current:{
name:new_test
}
}



$ b $ p
$ b


解决方案

是的,您可以使用点符号'到达对象:

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

您使用的查询语法也适用,但它具有不同的语义:它将匹配整个子文档,而不仅仅是一个字段。例如,下面的查询也会返回一个结果:

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

但是 db.collection .find({items:{old:{name:test}}})不会,因为 items 也包含当前字段。

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?

解决方案

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.

这篇关于在子文档中查找返回文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:06