简体   繁体   English

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

[英]How to append new value to a list in mongodb?

I want to insert a new element the "CarList" array below. 我想在下面的“ CarList”数组中插入一个新元素。 I am using MongoDB and dropwizzard in my project. 我在项目中使用MongoDB和dropwizzard。

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

My POJO classes: 我的POJO课程:

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;
}

My code to append a new entry in carList: 我的代码在carList中添加新条目:

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)));

The error that I am getting: 我得到的错误:

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class data.CarDetails] from JSON String; no single-String constructor/factory method (through reference chain: data.PropertyLedger["carList"])

From the error I can guess that the the wiring to CarDetails class is the issue. 从错误中我可以猜测到CarDetails类的接线是问题。 I am not sure how to solve it. 我不确定如何解决。 I have looked in updating nested documents in Mongo and similar links but could not find an answer. 我曾在Mongo和类似的链接中更新嵌套文档,但找不到答案。

Any pointers will be helpful. 任何指针都会有所帮助。 Thank you. 谢谢。

Try doing it using the $push operator for arrays in MongoDB. 尝试对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"))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM