San Jaisy
San Jaisy

Reputation: 17048

Delete the embedded document from the mongoDb using java

I have the below document and have a requirement to delete the Array item from the embedded document using MongoClient in micronaut application.

I want to delete the item with _id = 6044c50484116e3dfdc39d1b

{
    "_id": "6033c4b184116e3dfdc39d1a",
    "description": "Men description",
    "name": "Men",
    "subCategory": [{
            "name": "Sub category 1",
            "description": "Sub category description 4",
            "_id": "6033c50484116e3dfdc39d1b"
        },
        {
            "name": "Sub category 2",
            "description": "Sub category description 5",
            "_id": "6044c50484116e3dfdc39d1b"
        }
    ]
}

We can use $unset with BSON as below

Bson query = and(eq("_id", new ObjectId("6033c4b184116e3dfdc39d1a")),
                        eq("subCategory._id"), new ObjectId("6033c50484116e3dfdc39d1b")));

Single.fromPublisher(
                this.repository.getCollection(ConstantValues.PRODUCT_CATEGORY_COLLECTION_NAME, Category.class)
                        .updateOne(query, new Document("$unset", array))).subscribe();

Quite not sure how can I pass the value to the array or is there a better way to do that ?

Upvotes: 0

Views: 152

Answers (1)

San Jaisy
San Jaisy

Reputation: 17048

This is working for me

Bson query = and(
  eq("_id", new ObjectId("6033c4b184116e3dfdc39d1a")),  
  eq("subCategory._id", new ObjectId("6033c50484116e3dfdc39d1b"))
);

Single.fromPublisher(
             this.repository.getCollection(ConstantValues.PRODUCT_CATEGORY_COLLECTION_NAME, Category.class)
                        .updateOne(query, new Document("$pull",
                                new Document("subCategory",
                                        new Document(String.format("_%s","id"), new ObjectId(id))
                                ))
                        )).subscribe();

Upvotes: 1

Related Questions