我有一个具有以下形式的对象:
{
"_id": ObjectId("4fa43f4d1cf26a6a8952adf1"),
"userId": "1",
"facebookId": "1234",
"groups": [{
"groupName": "testGroup",
"members": [{
"memberFirstName": "userFirstName",
"memberLastName": "userLastName",
"memberDetails": {
"userId": "1",
"faceBookId": "1234"
}
}]
}]
}
这是一个为每个用户保存的集合 - 它的组,每个组都包含组成员......所以“组”键是一个数组(或列表),“成员”键也是如此。(每个用户可以有多个组,每个组有多个组成员)。
我很难用新的组成员更新对象,我想做的是:
db.collection.update({
userId: "1"
}, {
$push: {
"groups.members": {
membersDetails: {
userId: "2",
faceBookId: "54321"
},
memberFirstName: "UserB",
memberLastName: "UserBLastName"
}
}
});
但这似乎不起作用。
收到以下错误:
can't append to array using string field name [members]
我也在尝试使用 Java 驱动程序,但这似乎也不起作用。
DBObject query = new BasicDBObject("userId", "1");
DBObject newMemberDetailsObj = new BasicDBObject();
newMemberDetailsObj.put("userId", "2");
newMemberDetailsObj.put("faceBookId", "54321");
DBObject newMemberObj = new BasicDBObject();
newMemberObj.put("memberFirstName", "userB");
newMemberObj.put("memberLastName", "UserBLastName");
newMemberObj.put("memberDetails", newMemberDetailsObj );
DBObject update = new BasicDBObject("$push", new BasicDBObject("members", newMemberObj));
update.put("groupName", "testGroup");
DBObject maintain = new BasicDBObject("$push", new BasicDBObject("groups", update));
WriteResult newWr = coll.update(query, maintain);