删除mongodb中的特定嵌入对象

时间:2013-12-04 11:11:53

标签: java mongodb

这是我的java程序:

try {
    MongoClient mongoClient = null;
    mongoClient = new MongoClient( "localhost" , 27017);
    DB db = mongoClient.getDB("SchoolProject");
    boolean auth = db.authenticate("root", "root@123".toCharArray());
    System.out.println(auth);

    if(auth==true){
        DBCollection table = db.getCollection("Bus_route");
        BasicDBObject query = new BasicDBObject();
        query.put("BusId", "BUS_101");
        BasicDBObject data = new BasicDBObject();
        data.put("Route.$.stop_name", "hyderabad");
        data.put("Route.$.arrival_time", "1:05");
        BasicDBObject command = new BasicDBObject();
        command.put("$unset", data);

        table.update(query, command);
    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    System.out.println(e.getMessage());
}

和mongodb文件:

"BusId" : "BUS_101",
"DriverName" : "Alex",
"Route" : [
    {
        "stop_name" : "st. John Road",
        "arrival_time" : "10:30"
    },
    {
        "stop_name" : "hyderabad",
        "arrival_time" : "1:05"
    }
],
"SchoolName" : "St. John Paul",
"VehicleNo" : "A20y6757",
"_id" : ObjectId("529f093cdaa62b1b10b82cc1")

和 文件名:Bus_route

删除mongodb中的特定嵌入对象 如何在数组路径中删除名为hyderabad的对象而不删除其他对象?

在我从这个论坛得到帮助之后我得到了它,下面是代码

DBCollection table = db.getCollection("Bus_route");

BasicDBObject query = new BasicDBObject();
query.put("BusId", "BUS_101");

BasicDBObject data = new BasicDBObject();
data.put("stop_name", "hyderabad");

BasicDBObject command = new BasicDBObject();
command.put("$pull", new BasicDBObject("Route", data));

table.update(query,  command);

0 个答案:

没有答案