如何编写mongo查询

时间:2019-08-27 18:13:36

标签: mongodb

如何从下面的mongodb模式中获取特定电影的可用座位总数(该电影的所有影院中都有座位)。

我需要编写mongo查询以获取结果

{
    "_id" : ObjectId("5d637b5ce27c7d60e5c42ae7"),
    "name" : "Bangalore",
    "movies" : [
        {
            "name" : "KGF",
            "theatres" : [
                {
                    "name" : "PVR",
                    "seats" : 45
                },
                {
                    "name" : "IMAX",
                    "seats" : 46
                }
            ]
        },
        {
            "name" : "Avengers",
            "theatres" : [
                {
                    "name" : "IMAX",
                    "seats" : 50
                }
            ]
        }
    ],
    "_class" : "com.BMS_mongo.ZZ_BMS_mongo_demo.Entity.CityInfo"
}

我已经编写了以下代码:

db.cities.aggregate( [ 
    { "$unwind" : "$movies" }, { "$unwind" : "$theatres" } , 
    { "$group" : { _id : "$movies.theatre`enter code here`s.seats" , 
        total : { "$sum" : "$seats" } } 
    } 
] )

我的架构: image

3 个答案:

答案 0 :(得分:3)

以下查询可以为我们提供预期的输出:

db.collection.aggregate([
    {
        $unwind:"$movies"
    },
    {
        $unwind:"$movies.theatres"
    },
    {
        $group:{
            "_id":"$movies.name",
            "movie":{
                $first:"$movies.name"
            },
            "totalSeats":{
                $sum:"$movies.theatres.seats"
            }
        }
    },
    {
        $project:{
            "_id":0
        }
    }
]).pretty()

数据集:

{
    "_id" : ObjectId("5d637b5ce27c7d60e5c42ae7"),
    "name" : "Bangalore",
    "movies" : [
        {
            "name" : "KGF",
            "theatres" : [
                {
                    "name" : "PVR",
                    "seats" : 45
                },
                {
                    "name" : "IMAX",
                    "seats" : 46
                }
            ]
        },
        {
            "name" : "Avengers",
            "theatres" : [
                {
                    "name" : "IMAX",
                    "seats" : 50
                }
            ]
        }
    ],
    "_class" : "com.BMS_mongo.ZZ_BMS_mongo_demo.Entity.CityInfo"
}

输出:

{ "movie" : "Avengers", "totalSeats" : 50 }
{ "movie" : "KGF", "totalSeats" : 91 }

答案 1 :(得分:0)

agg pipeline

查询:

db.movie.aggregate([{ $unwind: {  path: "$movies",} }, 
{ $unwind: {  path: "$movies.theatres",} }, 
{ $group: {  _id: "$movies.name",  "moviename": { $first: "$movies.name"  },
"totalSeats": { $sum: "$movies.theatres.seats"  }} }])

答案 2 :(得分:0)

我通过此查询得到了答案...

db.cities.aggregate( [ 
    { "$match" : { "name" : "Bangalore" } },
    { "$unwind" : "$movies" } , 
    { "$match" : {"movies.name" : "KGF"} }, 
    { "$unwind" : "$theatres" },
    { "$group" : { _id : "$movies.name", total : { "$sum" : "$movies.theatres.seats" 
                  } } } 
] )