我有以下形式的对象:
{
"_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);