Update aggregate java - mongodb - $(update)

Viewed 297
db.getCollection('test').update({
},
[{$set:
    {
      books: {$concatArrays:[
                [],
                [{
                  "status": "available",
                  "shelf_id": "$shelf_id",
                  "rack_no": "$rack_no",
                  "book_id": new ObjectId()
                }]
      ]}
    }
}])

I am trying to convert the above query in Java. I am getting BatchCombiner exception.

Document findDoc = new Document();
        LinkedList<UpdateManyModel<Document>> docs = new LinkedList<UpdateManyModel<Document>>();
        String docId = new ObjectId().toString();
        Document objectIDDoc = new Document("book_id", docId).append("status", "active")
                .append("rack_no", "$rack_no"); 
                
        ArrayList<ArrayList<Document>> documents = new ArrayList<ArrayList<Document>>();
        ArrayList<Document> instanceList = new ArrayList<Document>();
        instanceList.add(objectIDDoc);
        documents.add(new ArrayList<Document>());
        documents.add(instanceList);
        Document instancesFinalDoc = new Document("instances", new Document("$concatArrays", documents));
        Document docToBeUpdated = new Document("$set", instancesFinalDoc);

I am not sure how to convert the list to Bson. Could anyone please help?

I am getting the below error:

com.mongodb.MongoBulkWriteException: Bulk write operation error on server vmwahcdb09-stg.corp.netapp.com:27016. Write errors: 
[BulkWriteError{index=0, code=52, message='The dollar ($) prefixed field '$concatArrays' in 'instances.$concatArrays' is not valid for storage.', details={}}]. 
1 Answers

You are almost there.

The error is reproducible if you try to update using older driver version. You need to do as below.

  1. Create a ClientSession

    ClientSession session = mongoClient.startSession()

  2. Then, whatever you have is perfectly correct. But You need to use updateMany latest one which supports aggregate

    writeCollection.updateMany(session, findBson, updateList, updateOptions);

For your case, you need to add docToBeUpdated to a List<Document> and use as updateList.

Related