MongoDB C # driver - Could Id Field Not Be Id?

Moreover, there is a class

class X {
       ....
       string Id { get; set; }
}

class Y : X {
       ObjectId MyId { get; set; }
}

I would like MyId to be an identifier for Y, i.e. displayed in _id.

Is it possible?

I get an exception after this code:

var ys = database.GetCollection("ys"); 
ys.InsertBatch(new Y[] { new Y(), new Y()}); 

Exception: {"Member 'MyId' of class 'MongoTest1.Y' cannot use the element name '_id' because it is already being used by the identifier 'Id'." }

Full test case:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;

namespace MongoTest1
{
    class X
    {
        public string Id { get; set; }
    }

    class Y : X
    {
        public ObjectId MyId { get; set; }
    }

    class Program
    {
        static Program() {
            BsonClassMap.RegisterClassMap<X>(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(cm.GetMemberMap(c => c.Id));
            });

            BsonClassMap.RegisterClassMap<Y>(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(cm.GetMemberMap(c => c.MyId));
            });
        }

        static void Main(string[] args)
        {
            var server = MongoServer.Create("mongodb://evgeny:evgeny@localhost:27017/test");
            var database = server.GetDatabase("test");

            using (server.RequestStart(database))
            {
                var ys = database.GetCollection("ys");
                ys.InsertBatch(
                        new Y[] {
                            new Y(), new Y()
                        }
                    );
            }
        }
    }
}

X Id MUST be a string.

+5
source share
1 answer

The answer to your question: "yes, but ...".

It is possible to have a member named Id that does not map to the _id element. For instance:

public class X {
    [BsonId]
    public ObjectId MyId;
}

public class Y : X {
    public string Id;
}

_id ( , _id).

+9

All Articles