1

I am trying to loop through id's in a collection for a MongoDb database. The goal is to loop trough these id's and use the id's to create a json files with the different id's. I believe the query that I wrote is returning all the id's, but then i get the below error.

Inner Exception 1:
FormatException: '9a1c458c-82Dd-43b4-a963-76a96d374580' is not a valid 24 digit hex string.

Below is my query to get all the id's

var thingsDoc = demoThings.AsQueryable().Where(a => a._id != null).ToList();

Below is my class of properties for Things

public class Things
    {
        [BsonRepresentation(BsonType.ObjectId)]
        public ObjectId _id { get; set; }
    }

I believe the issue is with how the properties are defined. Or maybe it is a problem with my query? From research I know the reason it is complaining is because of the dashes in the format. But not finding any work arounds to resolve this. Help is much appreciated.

hfires
  • 113
  • 10

2 Answers2

1

I've been able to resolve my issue. It seems that using a Model and doing a conversion between ObjectId and String was throwing off my program. So the below approach solved the issue.

var demoThings = DBConnect.CosmosClient.GetCollection<BsonDocument>("Things");
            foreach(var doc in demoThings.Find(x => x["_id"] != "").ToList())
            {
                thingList.Add(doc["_id"].ToString());
            }

My goal was to grab the collection and add all the _id's and add them to a list so that I could I simulate data in a json file and attach an id to the JSON. With the above i was able to grab the id's and them to a list.

hfires
  • 113
  • 10
0

Changing [BsonRepresentation (BsonType.ObjectId)] to [BsonId] will most likely solve your problem.

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

Difference between decorating a property in C# with BsonRepresentation(BsonType.ObjectId) vs BsonId vs ObjectId

Edit:

I created a simple working example. It's a model.

public class Model
{
    [BsonId]
    [BsonElement("id")]
    [BsonRepresentation(BsonType.ObjectId)]
    public ObjectId ID { get; set; }

    public Model(ObjectId id)
    {
        ID = id;
    }
}

This is a simple service class:

public interface IModelService
{
    Task<IEnumerable<string>> GetModelsIds();
    Task AddModel();
}

public class ModelService : IModelService
{
    private const string CollectionName = "Models";

    private readonly MongoClient client;
    private readonly IMongoDatabase _mongoDatabase;
    private readonly IMongoCollection<Model> _modelsCollection;

    public ModelService()
    {
        client = new MongoClient("mongodb://localhost:27017");
        _mongoDatabase = client.GetDatabase("MongoStackOverFlow");
        _productsCollection = _mongoDatabase.GetCollection<Model>(CollectionName);
    }

    public async Task<IEnumerable<string>> GetModelsIds()
    {
        var models =  await _productsCollection.Find(p => p.ID != null).ToListAsync();
        return models.Select(x => x.ID.ToString());
    }

    public async Task AddModel()
    {
        var model = new Model(new ObjectId());

        await _productsCollection.InsertOneAsync(model);
    }
}

And the entry point:

class Program
{
    static async Task Main(string[] args)
    {
        IModelService modelService = new ModelService();
        var modelsIds = await modelService.GetModelsIds();

        if (!modelsIds.Any())
        {
            for (int i = 0; i <= 10; i++)
            {
                await modelService.AddModel();
            }
        }

        Task.WaitAll();

        foreach (var modelId in modelsIds)
        {
            Console.WriteLine($"ProductID: {modelId}");
        }
    }
}
  • should my _id property be String or Object Id? – hfires Nov 20 '19 at 21:07
  • Ok, I have an another idea to change the your object id to string and name of the property to the Id, ID or something other than _id. – pkantorowicz Nov 20 '19 at 21:20
  • Do I keep [BsonId]? – hfires Nov 20 '19 at 21:22
  • now i get this error , 'Element 'x' does not match any field or property of class SimRunnerTest.Things.' – hfires Nov 20 '19 at 21:25
  • i tried adding this, [BsonRepresentation(BsonType.ObjectId)] and I got no errors. I have a piece of code adding all the id's to a list. but my list was empty – hfires Nov 20 '19 at 21:28
  • I have two new solutions, maybe now it's not a problem with the only id. Keep your actual implementation. In your query remove AsQueryable() and try using a Find() method instead of Where() or build a filter like this: `var filter = Builders.Filter.Ne("Id", BsonNull.Value);` and pass it to the Find() method. – pkantorowicz Nov 20 '19 at 21:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202761/discussion-between-hfires-and-pkantorowicz). – hfires Nov 20 '19 at 21:56