0

I have a collection like this.

      System
      {
           System_id: 100,

         system_type:
        {
             [ 
              { 
            Tenant_Id: 1, 
            Tenant_Info: "check", 
            Prop_Info: ...
              }, 
              { 
             Tenant_Id: 2, 
             Tenant_Info: "sucess", 
              Prop_Info: ...
              } ]
              }

I need to remove the only one embedded document where the tenant_id is 1 and system_id s 100 using java api.

I have tried to delete the document. But the whole document is getting deleted. I need to delete only the embedded document where tenant_id is 1.

            DBCollection collection=db.getCollection("system");
    field.put("system_id",100);
    field.put("system_type.Tenant_id", 1);
    collection.remove(field);

Kindly guide me how to delete it? I need the output like this.

            System
      {
           System_id: 100,

         system_type:
        {
             [ 
             { 
             Tenant_Id: 2, 
             Tenant_Info: "sucess", 
              Prop_Info: ...
              } ]
              }
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Ramya
  • 1,067
  • 6
  • 16
  • 29
  • 1
    This question is more or less the same as another SO post: [remove an entry from array using mongodb java driver][1] [1]: http://stackoverflow.com/questions/10097621/remove-an-entry-from-array-using-mongodb-java-driver – Steve Casey Sep 24 '12 at 01:04

2 Answers2

3

Since you're not deleting the whole document you need to call update with the $pull operator instead of remove:

BasicDBObject query = new BasicDBObject(
    "System_Id", 100
);

BasicDBObject pull = new BasicDBObject(
    "$pull", new BasicDBObject(
        "system_type", new BasicDBObject(
            "Tenant_Id", 1
        )
    )
);

collection.update(query, pull);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

Try something like this:

 { $pull : { system_type : {Tenant_Id: 1} } }
diederikh
  • 25,221
  • 5
  • 36
  • 49