Amar
Amar

Reputation: 971

Fetch mongo documents based on date

We are inserting mongo documents with identifier and there is a subarray within the documents.

insert 1 :

db.test.insert(
   {
        "companyId" : "123",
        "persons" : [
                {
                        "joiningDate" : NumberLong("1431674741623"),
                         "name" : "Rajesh"
                }
        ],

})

insert 2 :

db.test.insert(
   {
        "companyId" : "123",
        "persons" : [
                {
                        "joiningDate" : NumberLong("1431674741653"),
                         "name" : "Rahul"
                }
        ],

})

I would like to retreive the company details based on the company id and merge the persons into one array list, and sort the persons based on the joining date.

Currently I am able to retreive the data using QueryBuilder but I am unable to sort the person based on the date.I can use java comparator to do the same , but I am looking out if there is any API from mongo db java driver which can be used to get the same.

Thanks.

Upvotes: 0

Views: 141

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

you should use mongo aggregation like first $unwind persons array and then sort persons.joiningDate and then group with push as below :

db.test.aggregate({
  "$match": {
    "companyId": "123" // match companyId
  }
}, {
  "$unwind": "$persons" //unwind person array
}, {
  "$sort": {
    "persons.joiningDate": -1 //sort joining date
  }
}, {
  "$group": {
    "_id": "$companyId",
    "persons": {
      "$push": "$persons" //push all sorted data into persons
    }
  }
}).pretty()

For converting this code into java use mongo java aggregation as

// unwind  persons
DBObject unwind = new BasicDBObject("$unwind", "$persons");
// create  pipeline operations, with the $match companyId
DBObject match = new BasicDBObject("$match", new BasicDBObject("companyId", "123"));
// sort persons by joining date 
DBObject sortDates = new BasicDBObject("$sort", new BasicDBObject("persons.joiningDate", -1)); // -1 and 1 descending or ascending resp.
// Now the $group operation  
DBObject groupFields = new BasicDBObject("_id", "$companyId");
groupFields.put("persons", new BasicDBObject("$push", "$persons"));
DBObject group = new BasicDBObject("$group", groupFields);
// run aggregation
List < DBObject > pipeline = Arrays.asList(match, unwind,sortDates, group);
AggregationOutput output = test.aggregate(pipeline);
for(DBObject result: output.results()) {
  System.out.println(result);
}

Upvotes: 4

Related Questions