1

I am trying to execute following code:

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)
    ));

As I expected the output should not have duplicate sessionId values since I am using group by sessionId. But the problem is that the resulted output has duplicated sessionId values.

[
{
    "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"
}

  ]
garfbradaz
  • 3,424
  • 7
  • 43
  • 70
Kit
  • 273
  • 3
  • 5
  • 16
  • Here your grouping by `sessionId`, `time` and `makerId` so of course you get documents with same sessionId. The only way to get no duplicates is to group only by `sessionId` – felix Jul 12 '17 at 07:09
  • Actually i am new to nosql databases.According to relational databases if we put some fields in select field it should be included in groupby field.That is why i added all required fields to display inside group by field – Kit Jul 12 '17 at 07:14
  • I'm not sur to fully understand what your trying to achive here. Can you provide some samples documents from yout `chatLog` collection, and the expected output? – felix Jul 12 '17 at 07:16
  • I added the resulting out put.. – Kit Jul 12 '17 at 07:23
  • There you can see the sessionId having the duplicated values – Kit Jul 12 '17 at 07:24
  • Yes I got it, but what to you expect as result of your query ? – felix Jul 12 '17 at 07:25
  • I need to select displayName,sessionId,time,markerId while group by sessionId – Kit Jul 12 '17 at 07:29

1 Answers1

1

Try to group only by sessionId like this:

    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)
        ));
felix
  • 9,007
  • 7
  • 41
  • 62