2017-09-25 87 views
0

我需要在不同文档(MongoDB)中插入(或创建)一个字段。
这是我的代码:如何在查询中使用objectId .net

var myDB = mclient.GetDatabase("MasterDB"); 
var collection = myDB.GetCollection<BsonDocument>("MasterCollection"); 
var list = await collection.Find(new BsonDocument()) 
          .Limit(2) 
          .Skip(1) 
          .ToListAsync(); 

foreach (var docs in list) 
{    
    var updoneresult1 = await collection.UpdateManyAsync(
    Builders<BsonDocument>.Filter.Eq("_id", docs["_id"].ToString()), 
    Builders<BsonDocument>.Update.Push("OfficeCode", 
    Convert.ToInt32(txtOfficeCode.Text)));  
} 
+2

什么是你的问题?你有错误吗? –

+0

我没有错误,但它不起作用,我想知道如果我可以匹配docid的ObjectId与文档的ObjectId。我试图在2个不同的文档中添加“OfficeCode”字段 – fred

回答

0

我thiink你需要添加: http://api.mongodb.com/csharp/current/html/M_MongoDB_Bson_BsonDocument_Add_2.htm

foreach (var docs in list) 
{ 
    ....   
    docs.Add("OfficeCode", Convert.ToInt32(txtOfficeCode.Text)); 
    .... 
} 

PS我真的不知道你正试图在这里acomplish什么。

编辑:

在评论,你说你有麻烦通过_id匹配它。尝试改变

docs["_id"].ToString()

ObjectId.Parse(docs["_id"].ToString()) 
+0

它仍然无法正常工作,我试着用匹配另一个字段来代替ObjectId,它的工作原理..但现在我需要匹配“_id”字段 – fred