MongoTemplate 拉取查询

MongoTemplate pull query

我正在尝试从 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 }
)

现在我需要使用 spring 中的 mongo 模板来执行此操作, 我尝试了以下答案,但它不会删除该元素 MongoTemplate pull subdocument。 谁能建议我如何使用 spring 项目

中的 mongo 模板来实现此目的

您可以简单地使用以下查询来提取 vegetables 对象数组中的任何字符串:

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

在上面的query中,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 存储库:https://github.com/krishnaiitd/learningJava/blob/master/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/main/Application.java#L126