-10

我想向以下具有外键“用户”的文档添加一个新文档

{
  name:himani,
  User:[
    {
      _id:e25ffgf627627,
      Name:User1
    },
    {
      _id:fri2i2jhjh9098,
      Name:User2
    }
  ]
};

下面是我尝试将新文档添加到现有文档的代码。我的代码是:

var server = MongoServer.Create("mongodb://username:password@localhost:27017/?safe=true");
SafeMode mode = new SafeMode(true);
SafeModeResult result = new SafeModeResult();
var db = server.GetDatabase("himani");
var coll = db.GetCollection("test");
BsonDocument document = new BsonDocument();
document.Add("name", "himani");
result = coll.Insert(document, mode);

BsonDocument nested = new BsonDocument();
nested.Add("1", "heena").Add("2", "divya");
BsonArray a = new BsonArray();
a.Add(2);
a.Add(5);
nested.Add("values", a);
document["3"] = new BsonArray().Add(BsonValue.Create(nested));
coll.Save(document);
var query = Query.And(
    Query.EQ("name", "himani"),
    Query.EQ("3.1", "heena")
);
var match = coll.FindOne(query);

var update = Update.AddToSet("3", new BsonDocument {{ "count", "2" }});
coll.Update(query, update);

我想向 User 数组添加一个新文档。我正在通过上面的代码执行此操作,但它不起作用。请告诉我正确的方法。

4

1 回答 1

1

I don't understand your document structure at all... and the only "user" array I could find in here was a field called "3". Your code does in fact work and appends a document into the "3" array. The below is the result after running your code. Perhaps you could be more clear as to what you want your document to look like after you have "appended" a user.

{
  "_id":ObjectId("4fa7d965ce48f3216c52c6c7"),
  "name":"himani",
  "3":[
    {
      "1":"heena",
      "2":"divya",
      "values":[ 2, 5 ]
    },
    {
      "count":"2"
    }
  ]
}
于 2012-05-07T14:22:09.743 回答