简体   繁体   中英

MongoDB in Spring push array with update first then found object null

I'm updating a document with Spring's MongoTemplate

This is the code for updating a document(making array push for product comment);

public void saveProductComment(String productId,ProductComment comment){
    DBObject commentDBO = new BasicDBObject();

    mongoTemplate.getConverter().write(comment, commentDBO);

    mongoTemplate.updateFirst(
            Query.query(Criteria.where("_id").is(productId)),
            new Update().push("comment", commentDBO),
            Product.class);
}

Then I'm getting updated document but it returns null after the update. There is the code to finding all documents.

public List<Product> getAllProducts() {
        return mongoTemplate.findAll(Product.class, COLLECTION_NAME);
    }

Problem is that, when i updated the document , its storing order changes(Sorting alphabetically after update). For Example;

//Before Update
{
  name: {...} , 
  price: {...} ,
  comment: {[...]}
}
{
  comment: {[...]},
  name: {...} ,
  price: {...} ,
}

How can i achieve the document after the update. Are there any approach to finding document(s) with Spring's MongoTemplate or any alternative solution for that ? Thanks for your attention.

I found my own mistake;

While using update.push method , mongodb natively changing the field as an array , so then my find method couldn't find expected inserted class(eg. product.class). So i changed ProductComment property to ProductComment[] array in my Product.Class mongoDB found without problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM