嵌套查询mongodb数据

时间:2018-04-17 13:43:46

标签: java mongodb

我对mongodb和java都有点新意。我想查询关键的breaktime并找到值的总和。

 db.users90.find().pretty()
{
    "_id" : ObjectId("5ad5f2e2f58a542f7989e8fc"),
    "date" : "2018-04-17",
    "break" : [
            {
                    "out" : "18:00",
                    "in" : "18:40",
                    "breaktime" : "0:40"
            },
            {
                    "out" : "19:00",
                    "in" : "19:30",
                    "breaktime" : "0:30"
            }
    ]
}

我需要java中的帮助,添加那2个breaktime键(有些情况下可能会有n个文件中断) 0:40 + 0:30 = 0:70分钟

谢谢, 莫汉

1 个答案:

答案 0 :(得分:0)

虽然您需要的查询很简单,但将“breaktime”值存储为String,会使任何事情变得困难和复杂。

因此,假设您已将这些值存储为数字,例如。双,您可以像这样轻松地用Java执行查询;

AggregateIterable aggregationQuery = collection.aggregate(Arrays.asList(
        new Document("$match", new Document("date","yourDate")), // match a document with a specific date
        new Document("$unwind", "$break"), // decompose the 'break' array
        new Document("$group", new Document("_id", null).
              append("totalBreakTime", new Document("$sum","$break.breaktime")) 
)));
if (aggregationQuery.iterator().hasNext()){
      double totalBreakTime = ((Document)aggregationQuery.iterator().next()).get("break",Document.class).getDouble("breakTime");
}