我们可以查询值内的键

时间:2013-04-22 09:53:43

标签: mongodb

在我的文档中,如果键的值本身是json(具有键值)。 我如何在值内搜索文档的键。

代表:

    { "_id": { "$oid" : "51711cd87023380037000001" }, 
    "dayData": "{ "daysdata":{"date":"02-12-  2013","week_day":"","month":"","date_day":"","year":"2013"}}" 
    }

如果我有这样的多个文件,我想获得日期为“02-12- 2013”​​的文件。我的返回值应该是使用mongodb java驱动程序的密钥daydata的值

1 个答案:

答案 0 :(得分:2)

您可以使用点符号,所以在您的情况下:

db.collection.ensureIndex({'dayData.daysdata.date': 1});

然后

db.collection.find({'dayData.daysdata.date': 02-12-2013});

作为一个例子:

> db.test.insert({x: {x: {x: 1}}})
> db.test.insert({x: {x: {x: 2}}})
> db.test.insert({x: {x: {x: 3}}})
>
> db.test.ensureIndex({'x.x.x': 1})
> 
> db.test.find({'x.x.x': 2}, {_id: false})
  {"x" : { "x" : { "x" : 2} } }
> 

证明它使用索引:

> db.test.find({'x.x.x': 2}, {_id: false}).explain()
  {
    "cursor" : "BtreeCursor x.x.x_1",
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
        ....
  }
>