1

Here is the code :

AggregateIterable<Document> result = chatLogCollection.aggregate(Arrays.asList(
            new Document("$match", new Document("displayName", "user")),
            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)
    ));

This will generate the below type out put.

{
    "displayName": "test test",
    "_id": "123a54be-4b69-cd49-edb3-9b264fea077b",
    "time": {
        "$date": 1499759619016
    },
    "makerID": "xxxxx"
}

I need to format this to look like this:

{
    "displayName": "test test",
    "sessionID": "123a54be-4b69-cd49-edb3-9b264fea077b",
    "time": {
        "$date": 1499759619016
    },
    "makerID": "xxxxx"
}

That means i need to appear _id as sessionId. Please help me to do that.I am using mongoDB, java and windows 7.

Sunil Kanzar
  • 1,244
  • 1
  • 9
  • 21
Kit
  • 273
  • 3
  • 5
  • 16
  • question is probably duplicate or somewhat you are looking for. [see this one](https://stackoverflow.com/questions/15872301/how-to-rename-alias-fields-while-fetching-it-from-mongodb-through-query-using) – Omkar Mozar Jul 12 '17 at 10:16
  • 1
    at the end of your pipeline, add a **`$project`** stage like this : `{$project: {sessionId: "$_id", time: 1, makerID: 1}}` – felix Jul 12 '17 at 10:18
  • Actually I am new to mongodb. The example you are pointing is done with nodejs.I am using java here. – Kit Jul 12 '17 at 10:19
  • Possible duplicate of [How to rename/alias field(s) while fetching it from MongoDB through query using MongoDB-Node.JS native drive?](https://stackoverflow.com/questions/15872301/how-to-rename-alias-fields-while-fetching-it-from-mongodb-through-query-using) – sf_ Jul 12 '17 at 10:28
  • new Document("$project",new Document("sessionID","$_id").append("time",1).append("makerID", 1)) – Kit Jul 12 '17 at 10:31
  • Here it is displaying both _id and sessionId. Can i hide the _id – Kit Jul 12 '17 at 11:17
  • Yes, use `new Document("$project",new Document("sessionID","$_id").append("time",1).append("makerI‌​D", 1).append("_id", 0))`. Please use helpers and change to `import static com.mongodb.client.model.Aggregates.project; import static com.mongodb.client.model.Projections.*;` and use `project(fields(include("time", "makerI‌​D"), excludeId(), computed("sessionID", "$_id")));;` – s7vr Jul 12 '17 at 11:41
  • new Document("$project",new Document("sessionID","$_id").append("time",1).append(FIELD_MAKER_ID, 1)) – Kit Jul 12 '17 at 12:01
  • Here is my code .Please can you tell me how to format this according to your logic – Kit Jul 12 '17 at 12:02

0 Answers0