I am new to MongoDB, what I would like to do is Under property address I would like to save person's name and age, it might be one person per property or more than one, so I am trying with just name first but I am getting error.
Json
{
"property": "This is property address",
"address1": "address 1",
"address2": "address 2",
"city": "city name",
"people": [
"Person 1",
"Person 2",
"Person 3",
"Person 4"
]
}
C# code
List<string> names = new List<string>();
names.Add("person 1");
names.Add("person 2");
names.Add("person 3");
names.Add("person 4");
var document = new BsonDocument {
{"property", "10" },
{"address", "this is address 1" },
{"city", "city name" },
{"Family Members", new BsonArray {
new BsonDocument { {"name", names.ToBsonDocument() } }
} }
};
but I am getting bellow error
An Array value cannot be written to the root level of a BSON document.
look forward to you help.
AFAIK, You con use BsonArray(IEnumerable<string> strings)
constructor like this:
var names = new[]
{
"Person 1",
"Person 2",
"Person 3",
"Person 4"
};
var document = new BsonDocument
{
{"property", "10"},
{"address", "this is address 1"},
{"city", "city name"},
{"Family Members", new BsonArray(names)}
};
That result is:
{
{
"property" : "10",
"address" : "this is address 1",
"city" : "city name",
"Family Members" : ["Person 1", "Person 2", "Person 3", "Person 4"]
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.