0

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 ?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.