MongoTemplate拉式查询

时间:2019-11-25 14:40:33

标签: java spring mongodb spring-data-mongodb mongotemplate

我正在尝试从mongoDb的嵌入式字段数组中删除一个项目。数组是字符串类型,如下所示。

{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}

我只想从嵌入的蔬菜中去除胡萝卜。使用mongo shell,以下查询有效

db.stores.update(
    { },
    { $pull: { vegetables: "carrots" },
    { multi: true }
)

现在我需要在春季使用mongoTemplate执行此操作, 我尝试使用以下答案,但它不会删除该元素 MongoTemplate pull subdocument。 谁能建议我如何在春季项目中使用mongoTemplate实现此目标

1 个答案:

答案 0 :(得分:1)

您只需使用以下查询即可提取vegetables对象数组中的任何字符串:

mongoTemplate.updateMulti(new Query(), new Update().pull("vegetables", "squash"), "stores");

在上面的查询中,执行后将拉 squash 。有关详细信息,我还在上述查询之前和之后在stores集合上添加了查找查询:

    List<Stores> storesList = mongoTemplate.find(new Query(), Stores.class);
    for(Stores stores : storesList) {
      System.out.println(stores.toString());
    }
    mongoTemplate.updateMulti(new Query(), new Update().pull("vegetables", "squash"), "stores");
    List<Stores> afterModificationStoresList = mongoTemplate.find(new Query(), Stores.class);
    for(Stores stores : afterModificationStoresList) {
      System.out.println(stores.toString());
    }

输出如下:

2019-11-26 10:19:57.947 DEBUG 7321 --- [           main] o.s.data.mongodb.core.MongoTemplate      : find using query: { } fields: Document{{}} for class: class sample.data.mongo.models.Stores in collection: stores
Stores{id='1.0', fruits=[apples, pears, oranges, grapes, bananas], vegetables=[celery, squash]}
Stores{id='2.0', fruits=[plums, kiwis, oranges, bananas, apples], vegetables=[broccoli, zucchini, onions]}

2019-11-26 10:19:57.975 DEBUG 7321 --- [           main] o.s.data.mongodb.core.MongoTemplate      : Calling update using query: { } and update: { "$pull" : { "vegetables" : "squash" } } in collection: stores

2019-11-26 10:19:57.985 DEBUG 7321 --- [           main] o.s.data.mongodb.core.MongoTemplate      : find using query: { } fields: Document{{}} for class: class sample.data.mongo.models.Stores in collection: stores
Stores{id='1.0', fruits=[apples, pears, oranges, grapes, bananas], vegetables=[celery]}
Stores{id='2.0', fruits=[plums, kiwis, oranges, bananas, apples], vegetables=[broccoli, zucchini, onions]}

有关代码的详细信息,请访问Github repo:https://github.com/krishnaiitd/learningJava/blob/master/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/main/Application.java#L126