按字段值复制组

时间:2017-07-12 07:05:22

标签: java mongodb spring-data-mongodb mongodb-java mongodb-java-3.3.0

我正在尝试执行以下代码:

MongoDatabase db = MongoDatabaseConnector.getDatabase();
    MongoCollection<Document> chatLogCollection = db.getCollection("chatLog");

    AggregateIterable<Document> result = chatLogCollection.aggregate(Arrays.asList(
            new Document("$group", new Document("_id", new Document("sessionId", "$sessionGUID").append("time", "$ts").append("makerID", "$makerID"))),
            new Document("$sort", new Document("time", -1)),
            new Document("$skip", skip),
            new Document("$limit", limit)
    ));

正如我所料,输出不应该有重复的sessionId值,因为我使用的是sessionId组。但问题是结果输出重复sessionId个值。

[
{
    "displayName": "Unauthenticated User",
    "sessionId": "7b60615d-5909-1bf8-e5b9-6ee55e08452d",
    "time": {
        "$date": 1499759790117
    },
    "makerID": "NA"
},
{
    "displayName": "Unauthenticated User",
    "sessionId": "0a6b5db0-fecf-a7c2-9757-67e562b7e37e",
    "time": {
        "$date": 1499840350180
    },
    "makerID": "NA"
},
{
    "displayName": "Unauthenticated User",
    "sessionId": "0a6b5db0-fecf-a7c2-9757-67e562b7e37e",
    "time": {
        "$date": 1499840353438
    },
    "makerID": "NA"
}

  ]

1 个答案:

答案 0 :(得分:1)

尝试仅按sessionId分组:

    AggregateIterable<Document> result = chatLogCollection.aggregate(Arrays.asList(
                new Document("$group", new Document("_id", "$sessionGUID")
                        .append("time", new Document("$first", "$ts"))
                        .append("makerID", new Document("$first","$makerID"))),
                new Document("$sort", new Document("time", -1)),
                new Document("$skip", skip),
                new Document("$limit", limit)
        ));