如何检索和删除嵌入文档 spring 数据 mongodb

How to retrieve and remove embedded document spring data mongodb

我卡住了,如何删除 mongodb 中的嵌入文档。我正在使用 spring 数据 mongodb 标准,我这样做如下:

// database

"_id" : ObjectId("55683d51e4b0b6050c5b0db7"),
    "_class" : "com.samepinch.domain.metadata.Metadata",
    "preferenceType" : "SHOPPING",
    "subtypes" : [
        {
            "_id" : ObjectId("55683d51e4b0b6050c5b0db6"),
            "leftValue" : "VEG",
            "rightValue" : "NON_VEG",
            "preferencePoint" : 0
        }
    ],
    "createdDate" : ISODate("2015-05-29T10:20:01.610Z"),
    "updatedDate" : ISODate("2015-05-29T10:20:01.610Z")


// query

mongoTemplate.updateMulti(new Query(),
                    new Update().pull("subtypes", Query.query(Criteria.where("subtypes._id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class);

我做错了什么? 提前致谢!

subtypes 位于嵌套对象中,因此您应该首先将此传递给 $elemMatch 匹配给定条件的第一个匹配数组元素。将查询更新为:

db.updateMulti.update({"subtypes":{"$elemMatch":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}},
{"$pull":{"subtypes":{"_id":ObjectId("55683d51e4b0b6050c5b0db6")}}})

此查询从 subtypes 数组中提取完全匹配的数组元素。

在这个spring elemMatch的帮助下(在springmongo方面没有那么多专业知识)我在[=中转换了这个查询29=]格式如下:

mongoTemplate.updateMulti(new Query( 
where("subtypes").elemMatch(where("_id").is(ew objectId("55683d51e4b0b6050c5b0db6"))).pull(
  pull("subtypes", Query.query(Criteria.where("_id").is(new objectId("55683d51e4b0b6050c5b0db6"))),Metadata.class
));

上述 spring 查询未测试 希望您将 mongo 更新查询转换为 spring mongo 查询格式。