hfires
hfires

Reputation: 123

How to query MongoDb for id field and make a list of id's in c#

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.

Upvotes: 1

Views: 1620

Answers (2)

hfires
hfires

Reputation: 123

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.

Upvotes: 1

pkantorowicz
pkantorowicz

Reputation: 41

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}");
        }
    }
}

Upvotes: 0

Related Questions