如何为嵌入文档编写mongo查询

时间:2018-09-03 13:27:14

标签: mongodb nosql mongodb-query

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

{
  "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"}
       ]
    }

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

结果将是

Title      ISBN   
Mongo db   6563636222 
Linux      5555555

注意:我无法修改对象

1 个答案:

答案 0 :(得分:0)

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