假设我有这种文档结构,属性字段将是嵌入的文档我已经索引了属性。键和属性。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 })
查询结果不像我期望的那样,它应该只产生第二个文档,而不产生第一个文档。我知道我在属性上放了正则表达式。值,我期望它只检查属性。有地址值的键。
如果我想过滤另一个键,比如
db.app.find({ attributes.key:address , attributes.value:/.*uw.*/i , attributes.key:city , attributes.value:/.*ri.*/i })
任何意见都会对你们有帮助的。Thx . 我猜你需要$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"
}
只是调查了一下,得出了以下结论。下面使用下面提到的索引。您可以在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"
}