简体   繁体   English

在属性中带有 ObjectId 的 MongoDB 文档

[英]MongoDB document with ObjectId in atributes

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 创建此 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? 1-) 这样做有什么限制吗?

2-) If not, how can I "request" an ObjectID when inserting a new sensor?(Preferably using pymongo or Java/Kotlin-driver) 2-) 如果没有,我如何在插入新传感器时“请求”一个 ObjectID?(最好使用 pymongo 或 Java/Kotlin 驱动程序)

There's no restriction in doing this.这样做没有限制。 However, there's also no automated way to assign ObjectIDs to embedded documents in MongoDB.但是,也没有将 ObjectID 分配给 MongoDB 中嵌入文档的自动化方法。 So, you will have to manually create an ObjectID in your code before inserting items into the database.因此,在将项目插入数据库之前,您必须在代码中手动创建 ObjectID。

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.如果您可以控制架构,则可以通过向Sensor类添加ElementID字段并将它们存储在Sensors集合中来解决此限制。

I would just create a collection which stores each ID and a script that iterates through them.我只会创建一个集合来存储每个 ID 和一个遍历它们的脚本。 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.例如,您可以从 000001 开始,您的脚本(每次创建新传感器时都会运行)将获取最新值,将所述值分配给传感器 ID,将值加 1,然后存储结果它可用于创建下一个传感器 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM