Reputation: 157
I have a collection where my documents will have attributes that will have information that can be modified at any time, in my example I will call them "sensors".
{
_id: ObjectId("<document ObjectID>")
name: "Element name",
sensors: [
{
name: "Name sensor1",
value: "1.0"
},
{
name: "Name sensor2",
value: "2.0"
}
]
}
Each sensor can have its name and value changed anytime, in this case I would like to use an ID to identify each entry, and use ObjectId to create this id.
{
_id: ObjectId("<document ObjectID>")
name: "Element name",
sensors: [
{
name: "Name sensor1",
value: "1.0",
id: ObjectId(<this sensor id>)
},
{
name: "Name sensor2",
value: "2.0",
id: ObjectId(<another sensor id>)
}
]
}
This way, I can change name and value without lose track of which sensor is.
My questions are:
1-) Is there any restriction in doing it?
2-) If not, how can I "request" an ObjectID when inserting a new sensor?(Preferably using pymongo or Java/Kotlin-driver)
Upvotes: 0
Views: 52
Reputation: 1866
There's no restriction in doing this. However, there's also no automated way to assign ObjectIDs to embedded documents in MongoDB. So, you will have to manually create an ObjectID in your code before inserting items into the database.
If you have control over your schema, you could get around this limitation by adding an ElementID
field to your Sensor
class and storing them in a Sensors
collection.
Upvotes: 1
Reputation: 861
I would just create a collection which stores each ID and a script that iterates through them. For example, You could start with 000001, and your script(to be run each time you create a new sensor) would take in the most recent value, assign said value to sensor ID, add 1 to the value, then store the result so it can be used to create the next sensor ID.
Upvotes: 0