如何从嵌入文档的键值类型中获取准确的文档结果

时间:2013-05-14 09:30:25

标签: mongodb doctrine odm

假设我有这种文档结构,属性字段将是嵌入文档 我已经将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 })

查询结果不是我预期的,它应该只产生第二个文档而没有第一个文档。 我知道我把regex放在attributes.value上,我期待它只检查具有地址值的attributes.key。

如果我想过滤其他键,例如

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

任何意见都会对你有所帮助。 THX。

2 个答案:

答案 0 :(得分: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"
}

答案 1 :(得分: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"
}