2016-01-23 70 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" } ]} 
     ] 
    } 
); 
相關問題