More particulary, there is a class
class X {
....
string Id { get; set; }
}
class Y : X {
ObjectId MyId { get; set; }
}
I would like MyId to be an id for Y, i.e. to be mapped to _id.
Is it possible?
I get an exception after this code:
var ys = database.GetCollection("ys");
ys.InsertBatch(new Y[] { new Y(), new Y()});
The exception: {"Member 'MyId' of class 'MongoTest1.Y' cannot use element name '_id' because it is already being used by member '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's Id MUST be string.
Welcome to the documentation site for the official MongoDB C++ driver. You can add the driver to your application to work with MongoDB using the C++11 or later standard.
By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.
The mongocxx is a ground-up rewrite of a C++ driver for MongoDB based on libmongoc. It requires a C++11 compiler. It is known to build on x86 and x86-64 architectures for Linux, macOS, Windows, and FreeBSD.
The answer to your question is "yes, but...".
It is possible to have a member called Id which is not mapped to the _id element. For example:
public class X {
[BsonId]
public ObjectId MyId;
}
public class Y : X {
public string Id;
}
However, in a class hierarchy the _id member must be at the root of the hierarchy (in other words, all members of the hierarchy must agree on using the same _id).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With