2016-01-23 73 views
2

“users”集合具有包含数组字段的文档。查找其数组字段包含MongoDB中的一些子集的文档

示例文件:

{ 
    "_id" :1001, 
    "properties" : ["A", "B", "C", "D", "E", "F", "G", "H", "I"] 
} 
{ 
    "_id" : 1002, 
    "properties" : ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] 
} 

如何建立一个查询来获取随后的下一个条件的文件? 仅获得具有属性的文件:

[ "3" AND ("A" OR "1") AND ("B" OR "2") ] 

或以其他方式:

"3" AND "A" AND "B" 
OR 
    "3" AND "A" AND "2" 
OR 
    "3" AND "1" AND "B" 
OR 
    "3" AND "1" AND "2" 

在前面的例子中,查询已导致只有文档:

{ 
    "_id" : 1002, 
    "properties" : ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] 
} 

这个藏品有400万份文件。文档数组“属性”字段的平均长度为15个元素。我期待的查询必须在这个相当大的集合中有很好的表现。

回答

1

斯蒂芬的回答是确定的。

db.users.find(
    { 
    $and:[ 
     {"properties":"3"}, 
     {"properties" : {$in: ["A", "1"]}}, 
     {"properties" : {$in: ["B", "2"]}} 
    ] 
    } 
); 

而且

db.users.find(
    { 
     $or: [ 
     {"properties" : {$all: ["3", "A", "B"]}}, 
     {"properties" : {$all: ["3", "A", "2"]}}, 
     {"properties" : {$all: ["3", "1", "B"]}}, 
     {"properties" : {$all: ["3", "1", "2"]}} 
    ] 
    } 
); 

(你的子集的第二描述的翻译(您的子集的第一描述的翻译):其它方式使用$in$all运营商实现的结果)

恐怕我不知道哪一个能确保最佳性能。我希望你有和properties索引。

您可以尝试使用explain的较小集合上的查询来查看执行计划

2

试试这个:

db.users.find(
    { 
     $or: [ 
      {$and: [{ "properties": "3" }, { "properties": "A" }, { "properties": "B" }]}, 
      {$and: [{ "properties": "3" }, { "properties": "A" }, { "properties": "2" }]}, 
      {$and: [{ "properties": "3" }, { "properties": "1" }, { "properties": "B" }]}, 
      {$and: [{ "properties": "3" }, { "properties": "1" }, { "properties": "2" }]} 
     ] 
    } 
); 

db.users.find(
    { 
     $and: [ 
      {"properties": "3" }, 
      {$or: [ { "properties": "A" }, { "properties": "1" } ]}, 
      {$or: [ { "properties": "B" }, { "properties": "2" } ]} 
     ] 
    } 
); 
相关问题