【问题标题】:How to write mongo query for embed document如何为嵌入文档编写 mongo 查询
【发布时间】:2018-09-03 13:27:13
【问题描述】:

我有一个要求,我需要从不同的嵌入文档中选择不同的文件

{
  "isbn":"1234567890",
  "title":"Mongo db",
  "formats":[
      {"isMaster":"true",
      "digiform":"EBK",
      "isbn":"6563636222"},
      {"isMaster":"false",
      "digiform":"EBGE",
      "isbn":"333554445447"
      },
      {"isMaster":"false",
      "digiform":"HARD",
      "isbn":"776655440011"
      }
   ]
}

{
  "isbn":"11111",
  "title":"SQL",
  "formats":[
      {"isMaster":"false",
      "digiform":"EBK",
      "isbn":"22222"},
      {"isMaster":"false",
      "digiform":"EBGE",
      "isbn":"33333"
      },
      {"isMaster":"false",
      "digiform":"HARD",
      "isbn":"444444"
      }
   ]
}
 {
      "isbn":"AABB11",
      "title":"Linux",
      "formats":[
          {"isMaster":"true",
          "digiform":"EBGE",
          "isbn":"5555555"}
       ]
    }

我想获取 isMaster 为 true 的对象的 Title 和 ISBN,并且至少有一种格式对 digiform 具有 EBGE 的价值

所以结果是

Title      ISBN   
Mongo db   6563636222 
Linux      5555555

注意:我不能修改对象

【问题讨论】:

  • stackoverflow.com/search?q=mongo+query+embed+document 中的任何内容都适合您吗?
  • 我将如何从 isMaster true 和 digiform 与 EBGE 相同或其他对象的格式 objct 之一中选择 isbn
  • 你想获取所有isMaster为真的格式,另外一个条件是什么,你能解释得更清楚吗??
  • 使用聚合或 $elemMatch。前者允许重新塑造响应,后者更快。请阅读类似的答案。

标签: mongodb nosql mongodb-query


【解决方案1】:
db.state.aggregate(

// Pipeline
[
    // Stage 1
    {
        $unwind: {
            path : "$formats",
            preserveNullAndEmptyArrays : false 
        }
    },

    // Stage 2
    {
        $match: {
            "formats.isMaster":"true",
            "formats.digiform":"EBGE"
        }
    },

    // Stage 3
    {
        $group: {
            "_id":"$_id",
            "title":{$last:"$title"},
            "isbn":{$last:"$formats.isbn"}
        }
    },
]);

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2021-02-21
    • 2020-11-19
    相关资源
    最近更新 更多