首页 > 解决方案 > Mongo 查询访问模式中的嵌套数组

问题描述

以下是我拥有的 mongodb 架构

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

我想获取电影“复仇者联盟”在班加罗尔市可用座位的价值。查询应该返回我可用座位的整数值。

我写了这段代码

MongoClientURI mongoClientURI = new MongoClientURI("mongodb://localhost:27017");
MongoClient mongoClient = new MongoClient(mongoClientURI);  
MongoDatabase database = mongoClient.getDatabase("BMSdb");
MongoCollection<Document> collection = database.getCollection("cities");

AggregateIterable<Document> output = collection.aggregate(
                                            Arrays.asList(                                           
           Aggregates.match(Filters.eq("name" , cityname)),                                                  
           Aggregates.unwind("$movies"),                                                     
           Aggregates.match(Filters.eq("movies.name" , moviename)),                                                  
           Aggregates.unwind("$movies.theatres"),                                                    
           Aggregates.match(Filters.eq("movies.theatres.name" , cinemaname)),                                                    
           Aggregates.group("$movies.theatres.seats")
            )
        );

List<Object> res = new ArrayList<>();

for(Document d : output) {
    res.add(d.get("_id"));
}

Integer currentSeats = Integer.parseInt(res.get(0).toString());

“输出”有以下文件 -

Document{{_id=50}}

我能够检索座位数,但有没有其他方法可以仅使用 mongo 查询来获取可用座位...

我还需要更新座位......我该怎么做?

标签: javamongodbspring-boot

解决方案


推荐阅读