使用java驱动程序从mongodb中的数组中删除字段

时间:2014-08-08 21:27:59

标签: mongodb-query mongodb-java

我需要删除设备数组中的所有字段,这些字段的条件为state = 0

这是我的mongodb文件:

{ "_id" : { "$oid" : "53e53553b76000127cb1ab80"} ,  
  "city" : "Some Place" , 
  "devices" : 
       [ { "guid" : "local" , "brand" : "SSSS" , "state" : 1} , 
         { "guid" : "local2" , "brand" : "DDD" , "state" : 0} , 
         { "guid" : "local2" , "brand" : "DDD" , "state" : 0} ,   
         { "guid" : "local2" , "brand" : "DDD" , "state" : 0}] , 
  "phone": 8888888888,   
  "sex" : "Male"
 }

这是我正在尝试的java代码:

DBCollection collection = db.getCollection(usersCollection);
BasicDBObject query2 = new BasicDBObject("_id", id);
((BasicDBObject) query2).append("devices.guid", device);
((BasicDBObject) query2).append("devices.state", 0);
collection.remove(query2);

但是此查询会从文档中删除所有设备。 提前谢谢!

3 个答案:

答案 0 :(得分:2)

你需要做相同的事情:

db.usersCollection.update(
     {"_id":"yourId"}, 
     {$pull: 
            { "devices" : 
                    { $elemMatch : 
                        {
                          "guid":"local2", 
                          "state":"0"
                        }
                    }
            }
     }
)

yourId替换为您要查询的ID

也就是说,不要使用remove,而是update中使用$pullBasicDBObject。我现在无法测试,但尝试:

DBCollection collection = db.getCollection(usersCollection);
BasicDBObject query = new BasicDBObject("_id", id);

BasicDBObject deviceToDelete = new BasicDBObject("guid",device);
deviceToDelete.append("state", "0");

BasicDBObject obj = new BasicDBObject("devices", deviceToDelete);
collection.update(query, new BasicDBObject("$pull",obj));

让我知道这是否有效(再次我无法测试,因为我的机器上没有mongod)。

答案 1 :(得分:1)

我按照此answer

解决了问题

此代码有效:

    DBCollection collection = db.getCollection(usersCollection);
    BasicDBObject match = new BasicDBObject("_id", id);
    BasicDBObject update2 = new BasicDBObject("devices", new BasicDBObject("guid", device)
                                      .append("state", 0));
    collection.update(match, new BasicDBObject("$pull", update2));

答案 2 :(得分:1)

您不能使用remove-Function删除嵌入文档,而是需要使用更新。这是您需要在java中实现的函数调用:

db.userCollection.update(
{_id: ObjectId("53e53553b76000127cb1ab80")},
{$pull: 
    { devices : 
            {state: 0}
    }
})

请注意,update-function接受参数,第一个用于查找文档,第二个用于修改文档。

DBCollection collection = db.getCollection(usersCollection);
BasicDBObject query = new BasicDBObject("_id", newObjectID("53e53553b76000127cb1ab80"));

BasicDBObject condition = new BasicDBObject("state",0);
BasicDBObject array = new BasicDBObject("devices", condition);
BasicDBObject update = new BasicDBObject("$pull", array);

collection.update(query, update);

我没有测试Java代码,但我测试了mongoDB中的函数调用。 如果它不起作用,请先检查实现。