1

我正在尝试设置一个版本化文档的集合,只要有编辑操作,我就会在其中插入一个具有相同 id 和时间戳的新文档。我在 id 和 timestamp 字段上使用了唯一的复合索引。MongoError: E11000 duplicate key error每当我尝试将具有不同 id 但时间戳相同的文档插入另一个文档时,CosmosDB 都会给我。MongoDB 文档说我应该能够做到这一点:

https://docs.mongodb.com/v3.4/core/index-unique/#unique-compound-index

您还可以对复合索引强制执行唯一约束。如果您在复合索引上使用唯一约束,那么 MongoDB 将强制索引键值组合的唯一性。

我尝试使用非唯一索引,但资源管理器模板失败,说不支持非唯一复合索引。我正在使用 node.js 本机驱动程序v3.2.4。我也尝试使用 Azure Portal 插入文档,但收到了同样的错误。这让我相信 CosmosDB 和 node.js 驱动程序之间没有问题。

这是一个小例子来演示这个问题。我正在使用 Node 运行它v10.15.3

const { MongoClient } = require('mongodb');

const mongoUrl = process.env.COSMOSDB_CONNECTION_STRING;
const collectionName = 'indextest';

const client = new MongoClient(mongoUrl, { useNewUrlParser: true });
let connection;

const testIndex = async () => {
  const now = Date.now();
  connection = await client.connect();
  const db = connection.db('master');
  await db.collection(collectionName).drop();
  const collection = await db.createCollection(collectionName);
  await collection.createIndex({ id: 1, ts: -1 }, { unique: true });
  await collection.insertOne({ id: 1, ts: now, title: 'My first document' });
  await collection.insertOne({ id: 2, ts: now, title: 'My other document' });
};

(async () => {
  try {
    await testIndex();
    console.log('It works');
  } catch (err) {
    console.error(err);
  } finally {
    await connection.close();
  }
})();

我希望这两个插入操作能够工作并且程序以It works. 我得到的是一个错误:

{ MongoError: E11000 duplicate key error collection: master.indextest Failed _id or unique key constraint
    at Function.create (/home/node/node_modules/mongodb-core/lib/error.js:43:12)
    at toError (/home/node/node_modules/mongodb/lib/utils.js:149:22)
    at coll.s.topology.insert (/home/node/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
    at handler (/home/node/node_modules/mongodb-core/lib/topologies/replset.js:1155:22)
    at /home/node/node_modules/mongodb-core/lib/connection/pool.js:397:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  errmsg:
   'E11000 duplicate key error collection: master.indextest Failed _id or unique key constraint',
  [Symbol(mongoErrorContextSymbol)]: {} }

这是 CosmosDB 的 MongoDB API 中的预期行为还是错误?

4

0 回答 0