MongoDB C#驱动程序和服务器生成的ObjectId [英] MongoDB C# Driver and server generated ObjectIds

查看:200
本文介绍了MongoDB C#驱动程序和服务器生成的ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以获取服务器生成的ObjectId而不是C#驱动程序生成的ObjectId?使用MongoCollectionSettings.AssignIdOnInsert = false仅会使您清零ObjectIds.我正在对一个封闭的集合进行多线程插入,并且看到线程在ObjectId生成和插入之间切换.这会导致应该按自然顺序排序的带尾游标排序的集合中的ObjectIds乱序.现在,我正在为插入使用静态锁定对象,但这对不同的可执行文件/服务器无济于事.

Is there a way get server generated ObjectIds instead of C# Driver generated ObjectIds? Using MongoCollectionSettings.AssignIdOnInsert = false only gets you zeroed out ObjectIds. I'm doing multi-threaded inserts on a capped collection, and I'm seeing threads switch between the ObjectId generation and the insert. This causes out of order ObjectIds in a collection that's supposed to be ordered for tailed cursors sorting on natural order. Right now I'm using a static lock object for the inserts, but that won't help with different executables/servers.

似乎可以通过pymongo驱动程序实现:服务器在pymongo上生成的ObjectID

It appears this is possible with the pymongo driver: ObjectID generated by server on pymongo

推荐答案

从封顶的集合中按插入顺序获取文档

上限集合按插入顺序维护文档,因此理想情况下,您应该使用

Getting documents in insertion order from a capped collection

Capped collections maintain documents in insertion order, so you should ideally use natural order rather than relying on the timestamp in the generated _id. Your tailable cursor will be reading documents in natural order, so should not make any assumptions based on the _id.

要使用C#驱动程序在服务器端生成_id,您需要:

To generate _id on the server side using the C# driver you need to:

  • 设置类属性[BsonIgnoreIfDefault]
  • 设置收集属性AssignIdOnInsert = false
  • 插入没有_id
  • 的文档
  • set the class attribute [BsonIgnoreIfDefault]
  • set the collection attribute AssignIdOnInsert = false
  • insert a document without an _id

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;

public class MyDoc {
    [BsonIgnoreIfDefault]
    public ObjectId? Id;
    public int X;
}

public static class Program {
    public static void Main(string[] args) {
        MongoClient client = new MongoClient(); // connect to localhost
        var server = client.GetServer ();
        var database = server.GetDatabase("test");
        var collectionSettings = new MongoCollectionSettings { AssignIdOnInsert = false };
        var collection = database.GetCollection<MyDoc>("nullid", collectionSettings);

        // Insert document without _id
        collection.Insert(new MyDoc { X = 1});
    }
}

这篇关于MongoDB C#驱动程序和服务器生成的ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆