Mongo查询以访问架构中的嵌套数组

时间:2019-08-30 10:04:02

标签: java mongodb spring-boot

下面是我拥有的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查询来获得席位...

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

0 个答案:

没有答案