2017-09-25 45 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

相關問題