Convert list to BsonArray?

4,476 views
Skip to first unread message

Senor Cardgage

unread,
Jul 29, 2011, 8:05:53 PM7/29/11
to mongodb-csharp
I am trying to do this:

List<MyItems> items = GetAListOfMyItemsFromSomewhere();
BsonDocument cust1 = new BsonDocument();
cust1.Add("Items", items.ToBsonDocument());

This results in "System.InvalidOperationException : WriteStartArray
can only be called when State is Value, not when State is Initial".
How do I convert 'items' into a valid argument for the Add() method?

Robert Stam

unread,
Jul 29, 2011, 10:39:19 PM7/29/11
to mongodb-csharp
ToBsonDocument works one document at a time, you can't call it on the
whole list.

You could write it like this:

List<MyItems> items;
var cust1 = new BsonDocument();
cust1.Add("Items", new BsonArray(items.Select(i =>
i.ToBsonDocument())));

Sandip Agrawal

unread,
May 22, 2018, 1:57:24 AM5/22/18
to mongodb-csharp
Worked for me. Thanks
Reply all
Reply to author
Forward
0 new messages