EagleBP
EagleBP

Reputation: 151

Store a list of Guids in MongoDb as a list of strings

I want to store a list of Guids as a list of Strings in MongoDB. For a single Guid I use the following attribute:

[BsonRepresentation(BsonType.String)]
public Guid GuidId{ get; set; }

Is there an attribute to do the same with:

public List<Guid> GuidIdList { get; set; }

I found how you can do it with conventions but I really like to do it with an attribute:

How can I tell the MongoDB C# driver to store all Guids in string format?

Upvotes: 3

Views: 1656

Answers (1)

EagleBP
EagleBP

Reputation: 151

After a suggestion from someone at work, I've tried this with a small test:

[BsonRepresentation(BsonType.String)]
public List<Guid> GuidIds { get; set; }

Guess what, that is working! This is what you see in MongoDB:

{
  "_id" : ObjectId("5450fa00f0640335e4117d46"),
  "GuidId" : "f9e22da8-97c5-4dc7-ab26-ce5e095427a4",
  "GuidIds" : ["48e1d0a9-74a6-4b51-af6b-b217012adeac", "5e1751b1-d945-4baa-beed-847e9696caa9"]
}

So the attribute is working on the elements inside the list. I thought it would make a string-representation of the list itself.


Extra info, without the attribute

public List<Guid> GuidIds { get; set; }

You get this in MongoDB:

{
  "_id" : ObjectId("5450fc4bf0640327b82cb259"),
  "GuidId" : "e76f37a1-eba6-4afe-8ee4-8d431f97978c",
  "GuidIds" : [new BinData(3, "E4x6bMtj606H06snHwmVGw=="), new BinData(3, "uV9vktKLzkOF/ylcOckfYg==")]
}

Upvotes: 6

Related Questions