[英]How to specify _id and array of Object Ids as a composite primary key in MongoDB?
In the MongoDB database, a Collection was created, and inserted with some data: 在MongoDB数据库中,创建了一个Collection,并插入了一些数据:
>>> db.createCollection("Restaurants")
>> { "ok" : 1 }
>> db.Restaurants.insert({ "_id": "coolDinings",
>> "AppliedParameters": [ ObjectId("5617a7a52da21a733547b8da"),
>> ObjectId("5617a5102da21a733547b8d9") ], "Review": "excellent SeaFood", "Region": "USA" })
MongoDB default behaviour is to consider "_id" as the primary key. MongoDB的默认行为是将“ _id”视为主键。
However, I wanted a composite primary key consisting of the following fields: 但是,我想要一个由以下字段组成的复合主键:
"AppliedParameters" is an array of ObjectIds that can really vary in terms of number of ObjectIds it stores which can range from 0 to around 20 or 30 ObjectIds. “ AppliedParameters”是一个ObjectId数组,其存储的ObjectId数量实际上可以变化,范围可以从0到大约20或30个ObjectId。
I know the following code will create an index over both the aforementioned fields: 我知道以下代码将在上述两个字段上创建索引:
db.Restaurants.ensureIndex( { "_id": 1,"AppliedParameters": 1 }, { unique:true, sparse:true } );
However, my desire was to ensure that the aforementioned line of code will create a composite primary key. 但是,我希望确保上述代码行将创建一个复合主键。
In any case I ran the code. 无论如何,我都运行了代码。
In order to check if the composite key was created, I just reran the very first data insert again because I was hope it would complain by throwing an error related to composite primary key duplicates: 为了检查是否创建了复合键,我只是再次重新运行了第一个数据插入,因为我希望它会抛出与复合主键重复项有关的错误而抱怨:
>> db.Restaurants.insert({ "_id": "coolDinings",
>> "AppliedParameters": [ ObjectId("5617a7a52da21a733547b8da"),
>> ObjectId("5617a5102da21a733547b8d9") ], "Review": "excellent SeaFood", "Region": "USA" })
However, it only gave the following error: 但是,它仅给出以下错误:
E11000 duplicate key error index: test.Restaurants.$ id dup key: { : "coolDinings" } E11000重复键错误索引:test.Restaurants。$ id dup键:{:“ coolDinings”}
The aforementioned error seems to indicate that the "_id" is duplicated. 前面提到的错误似乎表明“ _id”已重复。 I want the Mongo client to state something along the lines of duplicate composite primary keys are Not allowed.
我希望Mongo客户端声明不允许重复的复合主键。
How do I go about the said task? 我该如何执行上述任务?
There's no "composite" primary keys in mongodb (in a sense that they span multiple fields). mongodb中没有“复合”主键(从某种意义上说,它们跨越多个字段)。
_id
is the one and only primary key. _id
是唯一的主键。
If you want a complex primary key, composed of several pieces of data, insert them all into the _id
field. 如果要由多个数据组成的复杂主键,请将它们全部插入
_id
字段中。
Note that _id
value can't be an array (must be one of primitives or an object). 请注意,
_id
值不能是数组(必须是基元或对象之一)。
{ _id: [1, 2, 3] }
{ _id: { a: 1, b: [2, 3] } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.