如何将新值附加到mongodb中的列表?

时间:2016-01-28 21:05:10

标签: mongodb mongo-java mongo-jackson-mapper

我想在下面插入一个新元素“CarList”数组。我在我的项目中使用MongoDB和dropwizzard。

Unsafe

我的POJO课程:

{
    "_id": "56aa6119bf78f37eee64697e",
    "name": "Jack",
    "occupation": "business*emphasized text* owner",
    "carList": [{
        "brand": "Ford",
        "cost": "$25000"
    }, {
        "brand": "Mazda",
        "cost": "$23000 "
    }]
}

我在carList中附加新条目的代码:

public class CarOwners {

    @ObjectId
    public String _id;
    public String name;
    public String occupation;
    public List<CarDetails> carList;
}

public class CarDetails
{
    public String brand;
    public String cost;
}

我得到的错误:

CarDetails newCarInfo = new CarDetails();
newCarInfo.brand="Toyota";
newCarInfo.cost="$20000";

BasicDBObject ownerQuery = new BasicDBObject("name", "Jack");
carOwnerCollections.update(ownerQuery, new BasicDBObject("$addToSet", new BasicDBObject("carList",newCarInfo)));

从错误中我可以猜到到CarDetails类的连接是个问题。我不知道如何解决它。我查看了updating nested documents in Mongo和类似的链接,但找不到答案。

任何指针都会有所帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用MongoDB中的数组的$push运算符。

BasicDBObject ownerQuery = new BasicDBObject("name", "Jack");
//Below code will insert the new object to the existing carList array
carOwnerCollections.update(ownerQuery, new BasicDBObject("$push", new BasicDBObject("carList",new BasicDBObject("brand","Toyota").append("cost","$20000"))));