集合内的MongoDB jsonarray长度

时间:2019-07-06 21:41:17

标签: mongodb mongodb-query

我在MongoDB中具有Collection,并且该集合中的每个文档都采用以下格式 { "_id" : { "$oid" : "4c6d8"} , "description" : "QUESTION" , "names" : [ "A" , "B" , "C" , "D" , "E" ]} 我想知道名字的数目

MongoClient mongoClient = new MongoClient(uri);
DB database = mongoClient.getDB(databasename);
DBCollection collection = database.getCollection(tablename);
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("description", "QUESTION");
DBCursor cursor = collection.find(whereQuery);
try {
while(cursor.hasNext()) {  
System.out.println(cursor.next())
}
} finally {
cursor.close();
}

我不知道如何计算姓名。预期结果-“ 5”

1 个答案:

答案 0 :(得分:0)

我不是编写Java代码的Java开发人员,但这是可在MongoDB查询编辑器中使用的查询。请将此查询插入您的代码中,然后将其检出。

db.collection.aggregate([
  {
    $match: {
      "description": "QUESTION"
    }
  },
  {
    $project: {
      NumberOfItemsInArray: {
        $size: "$names"
      }
    }
  }
])

结果

[
  {
    "NumberOfItemsInArray": 5
  }
]
相关问题