I have a tree-like document model like the image below. Is it possible to create a unique index for different layers? For example, in the below example, I have index field 1, then different index fields in objects of l2 array and l3 array. I am trying to create an index where index of all layers together should be unique. For example, if I have an index 1, I can't have the same index value throughout the child documents or any other documents. I tried searching a solution for it, but couldn't find any. Please help me with this issue. Thanks in advance.
Asked
Active
Viewed 42 times
0
-
You cannot. You are asking about https://jira.mongodb.org/browse/SERVER-14784. It's been there for some years already and here is no sign it's gonna be addressed any soon. – Alex Blex Dec 19 '19 at 09:34
1 Answers
0
I'm assuming you are using NodeJs and Mongoose since you did not specify that. You can get an ObjectId for every level by using different schemas in nested objects like the below example.
const level2Schema = new Schema({
unit: {
type: String,
required: true
},
price: {
type: Number,
required: true
}
});
const level1Schema = new Schema({
feildx: {
type: String,
required: true
},
anyNameArray: {
type: [level2Schema],
required: true
}
});
var MainSchema = new Schema(
{
field1: String,
field2: String,
anyNameArray: {
type: [level1Schema],
default: [],
required: true
},
},
{ timestamps: true }
);
This will create a unique ObjectId for every nested document.

Oshan Madusanka
- 327
- 3
- 9
-
I thought of this solution. But the requirements I am having to use the number as a unique value rather than object id. Because in the existing implementation, these numbers were used in lot other collections, and hence this situation – Sethuraman Srinivasan Dec 19 '19 at 08:14
-
well, just a thought. You can retrieve a timestamp from ObjectId and use that as a unique value. If you want to automate this process you might be able to use MongoDB change streams to listen for changes and save a timestamp-based unique key into the relevant document. – Oshan Madusanka Dec 19 '19 at 08:34