3

I am accessing MongoDB documents with a node.js web-front-end while in developement.

I got now following document:

{
   "_id": ObjectID("500abe6a25dff13c7c000001")
    , "username": "kyogron"
    , "email": "kyogron@example.de"
    , "contacts": [ObjectID("500abe6a2543213c7c000002")] // this should contain other user's id
}

I now want to add another user_id to the contacts array manually, before implementing the feature in the front-end.

As you see above I alread tried this using the ObjectID keyword but this didn't work...

4

2 回答 2

4

这从 MongoDB shell 对我有用,我使用$addToSet而不是$push因为我假设你想避免被骗:

var o = new ObjectId();
db.foo.update({}, {$addToSet : {"contacts" : o}});
var o = new ObjectId();
db.foo.update({}, {$addToSet : {"contacts" : o}});

这给了我一个看起来像这样的文档(我的 foo 集合只包含你的样本,所以我不必有特定的匹配标准):

{
    "_id" : ObjectId("500c2118c78bb07bfbb69eb3"),
    "contacts" : [
        ObjectId("500c20efc78bb07bfbb69eb2"),
        ObjectId("500c227ac78bb07bfbb69eb6")
    ],
    "email" : "kyogron@example.de",
    "username" : "kyogron"
}
于 2012-07-22T15:57:08.657 回答
1

在 mongo shell 中运行以下更新:

db.collection.update({"_id" : ObjectId("500abe6a25dff13c7c000001")},
                     {$push:{"contacts": ObjectId("500abe6a2543213c7c000002")}})

针对您的具体情况使用适当的 ObjectId 值。

于 2012-07-22T15:57:38.823 回答