CodeSlinger512
CodeSlinger512

Reputation: 668

MongoDB Error: "Subclass must implement GetDocumentID" when trying to insert List<string>

I am trying to add a simple list of strings:

string[] misc = {"a", "b", "c", "d"};
List<string> myList = new List<string>(misc);
mongo_collection.Insert(myList);

And it will return the error: "Subclass must implement GetDocumentID"

I tried this instead:

mongo_collection.InsertBatch(myList);

but it resulted in the same error. There has to be a way to insert this without creating a new class that inherits from List that implements GetDocumentID, right?

Thanks!

Upvotes: 0

Views: 561

Answers (2)

Robert Stam
Robert Stam

Reputation: 12187

The top level object being inserted into a collection must be an object that maps to a BSON document (not a BSON array).

Also, the top level object must always have an Id field (which maps to an element named _id).

To insert your data to the database you would define a class something like this:

public class C
{
    public ObjectId Id;
    public List<string> Strings;
}

and then you can insert the data like this:

var document = new C();
document.Strings = new List<string> { "a", "b", "c", "d" };
collection.Insert(document);

Note that the Id will be assigned a value automatically (as long as the Id is of a type like ObjectId that supports automatic generation of unique values).

Upvotes: 1

Nick Cipollina
Nick Cipollina

Reputation: 551

You are trying to put a List of type String into a mongo database. In order to add something to Mongo, it either has to be a Bson Object or you have to create a custom object, and map the properties so the Mongo knows how to convert your object into BSON.

Upvotes: 1

Related Questions