I'm trying to implement bulk update for a list of objects. But I'm getting the following error
java.lang.IllegalArgumentException: Invalid BSON field name bookingId
at org.bson.AbstractBsonWriter.writeName(AbstractBsonWriter.java:532)
at org.bson.codecs.BsonDocumentCodec.encode(BsonDocumentCodec.java:114)
at org.bson.codecs.BsonDocumentCodec.encode(BsonDocumentCodec.java:41)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:60)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
at com.mongodb.operation.BulkWriteBatch$WriteRequestEncoder.encode(BulkWriteBatch.java:398)
at com.mongodb.operation.BulkWriteBatch$WriteRequestEncoder.encode(BulkWriteBatch.java:377)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
The implementation for the updates are as follows:
public void _deleteAll( ArrayList<T> pojos ) {
Assert.notNull( pojos, "Entity must not be null!" );
BulkOperations ops = mongoTemplate.bulkOps( BulkOperations.BulkMode.ORDERED, className, collectionName );
for ( T pojo : pojos ) {
System.out.println( ( ( BaseEntity ) pojo ).get_id() );
( ( BaseEntity ) pojo ).setIsDeleted( true );
Query query = new Query( Criteria.where( "_id" ).is( ( ( BaseEntity ) pojo ).get_id() ) );
Document document = Document.parse( pojo.toString() ); //toString() returns JSON string
Update update = Update.fromDocument( document );
ops.updateOne( query, update );
}
ops.execute();
}
Second approach with WriteModel
public void _deleteAll( ArrayList<T> pojos ) {
MongoCollection<Document> collection = mongoTemplate.getCollection( collectionName );
List<WriteModel<Document>> writes = new ArrayList<>();
for ( T pojo : pojos ) {
( ( BaseEntity ) pojo ).setIsDeleted( true );
writes.add(
new UpdateOneModel<Document>(
new Document().append( "_id", ( ( BaseEntity ) pojo ).get_id() ), Document.parse( pojo.toString() )
)
);
}
collection.bulkWrite( writes );
}
The JSON data is similar to this:
{
"_id" : ObjectId("5d81d87ac290c518433e66d9"),
"bookingId" : 100344391,
"body" : "{\"title\”:\"Some title\”,\”booking_room_id\":null,\”message\”:\"some message\”}",
“nestedObject" : {
“someKey" : “some value"
},
"created_at" : ISODate("2019-09-18T07:10:50.067Z"),
"updated_at" : ISODate("2019-09-18T07:28:16.062Z"),
"isDeleted" : false,
"_class" : "com.test.mongo_test.entity.mongo.SomePojo"
}
Found the answer here . Basically what I had to do was add the query command $set
in the document.
writes.add(
new UpdateOneModel<>(
new Document( "_id", new ObjectId( id ) ),
new Document( "$set", Document.parse( pojo.toString() ) )
)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.