简体   繁体   中英

.net core application needs to talk to mongodb existing collection with _id and id

I've got a question. I have an existing mongodb collection I need to talk to containing an _id objectId and a UUID saved as string id field.

example

I need to fetch the documents based on a list of uuids -> which are basically the uuids in the id field of the document.

I've made a gateway to do this. (don't mind the TryAsync thingy that's basically a monad wrapped around a task)

public TryAsync<IEnumerable<T>> ByIds(List<Guid> ids)
    {
        var filter = Builders<T>.Filter.In("id", ids.Select(id => id.ToString()));
        return TryAsync<IEnumerable<T>>.Apply(() => new List<T>()).SetAsync(() => Collection.Find(filter).ToListAsync());

    }

The T is basically:

public interface IDomainObject
{
    string id { get; set; }
}

When I run the code I get no result back.

So I decided to do some more testing, I've added the _id as well and tried to fetch it based on a fix _id.

Then I get this message => MongoDB.Bson.BsonSerializationException: 'The property 'Id' of type 'RG.Product.Core.Process.Product' cannot use element name '_id' because it is already being used by property '_id''

Seems like you can't have an _id and id on the same object?

I'm not interested in the _id object id, I just want to fetch the document without the _id field based on the id. Hopefully somebody can point me in the right direction?

Have a look at the attributes you can use in MongoDB.

public class DBInfo
{
    [BsonId]                // With this attribute you can define the _id field name
    public ObjectId recordId;

    [BsonIgnore]
    public DBInfo child;    // Ignore this variable

    [BsonElement("sp")]     // Rename this variable
    public string searchPolicy;

    [BsonExtraElements]     // I always add this attribute on object with Id, this avoid deserialization exception in case of schema change
                            // All element the deserialization can't match will be added here
    public BsonDocument catchAll; 
}

https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/01%20-%20Begin/04%20-%20Attributes.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM