2016-01-28 38 views
0

我想在下面插入一个新元素“CarList”数组。我在我的项目中使用MongoDB和dropwizzard。如何将新值附加到mongodb中的列表中?

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

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

我的代码追加在卡洛斯的新条目:

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

,我得到的错误:

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"]) 

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

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

回答

0

请尝试使用$push运算符为MongoDB中的数组执行操作。

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