简体   繁体   English

从 basicdblist Mongo 中检索值

[英]Retrieving values from basicdblist Mongo

{
DB db = Helper.connectingMonggo();
BasicDBObject query = new BasicDBObject();
query.put("_id", "123");
DBCollection table = new db.getCollection("prodDetail");
DBCursor cursor = table.find(query); --// cursor has only one record (size =1)

while(cursor.hasNext()){
  DBObject obj = cursor.next();
  List<String> upcs = new ArrayList<>();
  BasicDBList list = (BasicDBList) obj.get("prodList"); --//here prodList size also 1 always
  DBObject obj1 = (DBObject) list.get(0);
  BasicDBList detailsList = (BasicDBList) obj1.get("pDetailsList");

 for(Object obj2 : detailsList){
   JSONObject obj3 = new JSONObject(JSON.serialize(obj2));
   ups.add(obj3.get("upcStatus").toString());
 } } }

I am getting the list array with upcStatus but, is it proper way to write?我正在使用 upcStatus 获取列表数组,但是,它是正确的书写方式吗?

This is an aggregation query using the MongoDB Java driver v3.12 and MongoDB v4.2.这是使用 MongoDB Java 驱动程序 v3.12 和 MongoDB v4.2 的聚合查询。 Note the result is returned using a single query and no additional code.请注意,结果是使用单个查询返回的,没有其他代码。 This is useful as the query is entirely run on the server and the result is returned to your Java application.这很有用,因为查询完全在服务器上运行,结果将返回到您的 Java 应用程序。

try(MongoClient mongoClient = MongoClients.create()) {
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection<Document> coll = database.getCollection("testCollection");
    List<Bson> pipeline = Arrays.asList(
        Aggregates.match(Filters.eq("_id", 123)),
        Aggregates.project(Projections.fields(
            Projections.excludeId(), 
                Projections.computed("upcStatus", Filters.eq("$arrayElemAt", 
                    Arrays.asList("$prodList.pDetailsList.upcStatus", 0L))
                )
        ))
    );
    
    Document doc = coll.aggregate(pipeline).first();
    System.out.println(doc.toJson());    // prints the array of upcStatus field values
}

The classes used in the code are defined as following classes or in packages: org.bson.Document , org.bson.conversions.Bson , com.mongodb.client.model.* and com.mongodb.client.* . The classes used in the code are defined as following classes or in packages: org.bson.Document , org.bson.conversions.Bson , com.mongodb.client.model.* and com.mongodb.client.* .

Also, note the try statement-block opens the connection to the server and closes automatically at the end of the try-block.另外,请注意try语句块打开与服务器的连接,并在 try 块结束时自动关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM