2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Insert array elements in sorting order in MongoDB using java driver

Currently I am facing issue with pushing of Array elements with sorting order in MongoDB. Instead preserving the insertion order I want to sort the arrays and insert into the document simultaneously. I found the solution from mongodb to use "$each" and  "$sort". But I need some piece of sample code to know the way of java implementation by using those attributes to resolve my issue.
userimage

Here is the solution for you. I just written some dummy piece of code and tested too. Just modify according to your project requirement and proceed. 


MongoClient mongoClient = new MongoClient();

MongoDatabase database = mongoClient.getDatabase("xxx");


MongoCollection<Document> dbCollection = database.getCollection("score_card");


Document queryFilter = new Document("_id","xxx");
Document newDocument = new Document();

newDocument.put("card_number", "4005");

newDocument.put("name_on_card", "xxx");


List<Document> list = new ArrayList<Document>();

list.add(newDocument);


Document sortedArrayObjet = new Document();

sortedArrayObjet.put("$each", list);

sortedArrayObjet.put("$sort", new Document("card_number", 1));


dbCollection.updateOne(queryFilter, new Document("$push",new Document("cards",sortedArrayObjet)));

Answer is