2013-05-19 30 views
0

我一直在使用MongoDB的刚刚开始,有一个问题...我怎么做到以下几点:C#MongoDB的多个类似的记录

var testrec = new TestClass 
{ 
    Name = "John", 
    Address = "10 Here St", 
    RecordType = "A" 
}; 

db.Save(testrec); 

testrec.RecordType = "B"; 
db.Save(testrec); 

我想第二保存,保存为一个新的文件,所以应该2个文档具有除RecordType以外的相同详细信息。

似乎发生的是它只是覆盖第一个文件。

有人可以让我知道。

感谢 院长

+0

你使用的是C#接口还是Mongo Javascript shell? – Thilo

回答

0

你只需要新增另一个Id,它会插入而不是更新。这里是一个完整的例子:

using System; 
using MongoDB.Bson; 
using MongoDB.Driver; 

namespace MongoTest 
{ 
    class TestClass{ 
     public string Name; 
     public string Address; 
     public string RecordType; 
     public ObjectId Id; 
    } 

    class MainClass 
    { 
     public static void Main (string[] args) 
     { 
      var connectionString = "mongodb://localhost"; 
      var client = new MongoClient(connectionString); 
      var server = client.GetServer(); 
      var db = server.GetDatabase("test"); 
      var collection = db.GetCollection("test"); 

      var testrec = new TestClass 
      { 
       Name = "John", 
       Address = "10 Here St", 
       RecordType = "A", 
       Id = new ObjectId() 
      }; 

      collection.Save(testrec); 
      testrec.Id = new ObjectId(); 
      testrec.RecordType = "B"; 
      collection.Save(testrec); 
      testrec.Id = new ObjectId(); 
      testrec.RecordType = "C"; 
      collection.Save(testrec); 
     } 
    } 
} 
0

当您保存的头文件,它就会被分配一个_id

当您使用现有的_id保存文档时,这是一个更新。

要插入新文档,请将所有字段(不含_id)复制到新的数据结构中,或者取消设置之前生成的_id