【问题标题】:Find documents whose array field contain some subsets in MongoDB在 MongoDB 中查找其数组字段包含某些子集的文档
【发布时间】:2016-01-24 16:50:49
【问题描述】:

“用户”集合包含带有数组字段的文档。

示例文件:

{
    "_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 个元素。我要找的查询在这个相当大的集合中一定有不错的表现。

【问题讨论】:

    标签: arrays mongodb


    【解决方案1】:

    Stephan 的回答还可以。使用$in$all 运算符实现结果的其他方法:

    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"]}}
        ]
        }
    );
    

    (您对子集的第二个描述的翻译)

    恐怕我不知道哪一个能确保最好的性能。我希望您在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" } ]}
              ]
          }
      );
      

      【讨论】:

        猜你喜欢
        • 2016-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多