2011-06-07 25 views
14

¿Cómo puedo agregar BsonArray a BsonDocument en MongoDB usando un controlador C#? Quiero un resultado algo como estoAgregar BSON matriz a BsonDocument en MongoDB

{ 
    author: 'joe', 
    title : 'Yet another blog post', 
    text : 'Here is the text...', 
    tags : [ 'example', 'joe' ], 
    comments : [ { author: 'jim', comment: 'I disagree' }, 
       { author: 'nancy', comment: 'Good post' } 
    ] 
} 
+0

¿Puedes aclarar tu pregunta? ¿Que estás tratando de hacer? ¿Cree el documento descrito arriba a través de BsonDocument? ¿O estás tratando de agregar comentarios al autor existente? Mb su código de programa ... –

Respuesta

15

Puede crear el documento anterior en C# con la siguiente afirmación:

var document = new BsonDocument { 
    { "author", "joe" }, 
    { "title", "yet another blog post" }, 
    { "text", "here is the text..." }, 
    { "tags", new BsonArray { "example", "joe" } }, 
    { "comments", new BsonArray { 
     new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } }, 
     new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } } 
    }} 
}; 

se puede comprobar si se ha obtenido el resultado de escritura con:

var json = document.ToJson(); 
+0

También agregaría que los valores nulos se ignoran por defecto. –

3

también puede agregar la matriz después de que ya exista BsonDocument, así:

BsonDocument doc = new BsonDocument { 
    { "author", "joe" }, 
     { "title", "yet another blog post" }, 
    { "text", "here is the text..." } 
}; 

BsonArray array1 = new BsonArray { 
     "example", "joe" 
    }; 


BsonArray array2 = new BsonArray { 
     new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } }, 
     new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } } 
    }; 


doc.Add("tags", array1); 
doc.Add("comments", array2); 
+0

ayudó a crear una matriz bson sin tener un bsondocument dentro. –