How to add a BsonDocument with a MongoDBRef in

887 Views Asked by At

I try to add document with C# on my MongoDB database. I want to add those documents with a DBRef in. Like this : MongoCompass Screen

Now, I add documents like this :

        var client = new MongoClient("mongodb://10.194.157.199:27017");
        var database = client.GetDatabase("DB");
        var produit = database.GetCollection<BsonDocument>("Produit");
        DBAccess data = new DBAccess();
        data.Connect();
        DataTable Produit = data.GetProduit();

        foreach (DataRow row in Produit.Rows)
        {
            var document = new BsonDocument
                {
                    { "Name", Convert.ToString(row.ItemArray[0]) },
                    { "Constructor", Convert.ToString(row.ItemArray[1]) },
                    { "Familly", Convert.ToString(row.ItemArray[2]) },
                };
            produit.InsertOne(document);
        }

To explain the goal of this, it's to connect information with a BI software and MongoDB.

If something is not clear, ask me. I will try to answer with my best English

Thank you.

1

There are 1 best solutions below

0
On

OK guys, I changed my code. I created classes to represent my differents collections.

public class MyClass
    {
        public MongoDBRef productID { get; set; }
        public string className{ get; set; }
        public int classNum { get; set; }
    }

and i use it like this :

static void Main(string[] args)

{
    var client = new MongoClient("mongodb://10.X.X.X:27017");
    var database = client.GetDatabase("MyDataBase");
    var myCollection = database.GetCollection<BsonDocument>("MyCollectionName");

    var document = new MyClass
    {
        ProductID = new MongoDBRef("Product", new ObjectId("k9ff635f18fg12c56hjf3fae")),
        className = "name",
        classNum = 21
    };
    myCollection.InsertOne(document.ToBsonDocument());
}