0

假设我有这种结构的文档,属性字段将是嵌入的文档,我已经索引了 attributes.key 和 attributes.value

1-------------------------------------------------------------------------------------
{ 
  "_id" : ObjectId( "5191d8e5d00560402e000001" ),
  "attributes" : [ 
  { "key" : "pobox","value" : "QaKUWo" }, 
  { "key" : "city", "value" : "CBDRip" }, 
  { "key" : "address","value" : "zmycAa" } ],
  "email" : "FWAUdl_2@email.com",
  "firstname" : "FWAUdl_2" 
}
2-------------------------------------------------------------------------------------
{ 
  "_id" : ObjectId( "5191d8e7d00560402e000055" ),
  "attributes" : [ 
    { "key" : "pobox", "value" : "sNFriy" }, 
    { "key" : "city", "value" : "JPdVrI" }, 
    { "key" : "address", "value" : "phOluW" } ],
  "email" : "hqYNWH_86@email.com",
  "firstname" : "hqYNWH_86" 
}

我的问题是如何在仅基于属性字段进行查询时获得准确的文档,

db.app.find({ attributes.key:address , attributes.value:/.*uw.*/i })

查询结果与我预期的不一样,它应该只产生第二个文档而没有第一个文档。我知道我将正则表达式放在attributes.value 上,我期望它只检查具有地址值的attributes.key。

如果我想过滤另一个键怎么办,比如,

db.app.find({ attributes.key:address , attributes.value:/.*uw.*/i , attributes.key:city , attributes.value:/.*ri.*/i })

任何意见都会对人有所帮助。谢谢。

4

2 回答 2

1

我猜你需要 $elemMatch ( http://docs.mongodb.org/manual/reference/operator/elemMatch/ )

db.test123.find({ attributes : { $elemMatch : { 'key':"address" , 'value':/.*uw.*/i } } }).pretty()
{
    "_id" : ObjectId("5191d8e7d00560402e000055"),
    "attributes" : [
        {
            "key" : "pobox",
            "value" : "sNFriy"
        },
        {
            "key" : "city",
            "value" : "JPdVrI"
        },
        {
            "key" : "address",
            "value" : "phOluW"
        }
    ],
    "email" : "hqYNWH_86@email.com",
    "firstname" : "hqYNWH_86"
}
于 2013-05-14T10:50:26.463 回答
0

只是调查了一下,然后想通了。下面使用下面提到的索引。您可以在 find() 上执行 explain() 以检查更多索引使用详情

db.testing.getIndexKeys()
[ { "_id" : 1 }, { "attributes.key" : 1, "attributes.value" : 1 } ]

test:Mongo > db.testing.find({$and : [ { attributes : {$elemMatch : {key : 'address', value : /.*uw.*/i }} }, { attributes : {$elemMatch : {key : 'city', value : /.*ri.*/i }} }] }).pretty()
{
    "_id" : ObjectId("5191d8e7d00560402e000055"),
    "attributes" : [
        {
            "key" : "pobox",
            "value" : "sNFriy"
        },
        {
            "key" : "city",
            "value" : "JPdVrI"
        },
        {
            "key" : "address",
            "value" : "phOluW"
        }
    ],
    "email" : "hqYNWH_86@email.com",
    "firstname" : "hqYNWH_86"
}
于 2013-05-15T10:37:29.820 回答