【问题标题】:Insert a document into another document in MongoDB将一个文档插入到 MongoDB 中的另一个文档中
【发布时间】:2015-12-19 16:07:29
【问题描述】:

我正在尝试在另一个文档中添加一个文档。

我正在尝试将一个新文档插入到文档sensor_collection 中,其中时间戳作为键,光代理和临时作为该文档的内容。

我的代码不起作用是合乎逻辑的,因为我正在设置一个新的sensor_collection。有谁知道我如何在sensor_collection 中设置时间戳文档,还是建议不要这样做?

这是代码:

MongoCollection<Document> collection  =  db.getCollection(Sensor.KEY_COLLECTION);
    //append sensor data to existing document
    collection.updateOne(doc, new Document("$set",
            new Document("sensor_collection", new Document(
                    String.valueOf(stamp.getCurrentTime()), new Document(
                            Sensor.KEY_LIGHT, sensorData.getLight())
                            .append(Sensor.KEY_PROX, sensorData.getProx())
                            .append(Sensor.KEY_TEMP, sensorData.getTemp())
                    ))));

目前,此代码会覆盖数据库中已经存在的时间戳。

【问题讨论】:

  • 我有点迷路了。要将新文档附加到现有集合吗?
  • 嘿,在 sensor_collection 中我想要多个时间戳,每个时间戳都包含光照、代理和温度。我想向 sensor_collection 添加另一个时间戳对象。

标签: java mongodb mongodb-java mongo-collection


【解决方案1】:

如果要附加到现有的嵌入式集合,请使用 $push 而不是 $set$push 运算符将指定的值附加到数组。像这样的:

collection.updateOne(doc, new Document("$push",
            new Document("sensor_collection", new Document(
                    String.valueOf(stamp.getCurrentTime()), new Document(
                            Sensor.KEY_LIGHT, sensorData.getLight())
                            .append(Sensor.KEY_PROX, sensorData.getProx())
                            .append(Sensor.KEY_TEMP, sensorData.getTemp())
                    ))));

有关 mongo 更新操作符的更多详细信息,check this out

【讨论】:

  • 您好,谢谢您的回答。如果 sensor_collection 是一个数组,则 $push 有效。它是一个对象。是否仍然可以向 sensor_collection 添加另一个时间戳对象?不使用数组。还是使用数组是更常见的方法?
  • 您可以选择嵌入式集合而不是整个集合,然后更新它。可能这行得通,但我猜使用数组会更简单
【解决方案2】:

the Mongodb documentation 我发现了这个:

“要在嵌入文档或数组中指定&lt;field&gt;,请使用点表示法。”

我使用了 $set 运算符。我正在设置 sensor_collection.timestamp

MongoCollection<Document> collection  =  db.getCollection(Sensor.KEY_COLLECTION);
    //append sensor data to existing document
    collection.updateOne(doc, new Document("$set",
            new Document("sensor_collection."+String.valueOf(stamp.getCurrentTime()),
                     new Document(
                            Sensor.KEY_LIGHT, sensorData.getLight())
                            .append(Sensor.KEY_PROX, sensorData.getProx())
                            .append(Sensor.KEY_TEMP, sensorData.getTemp())
                    )));

这行得通。给:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2021-10-25
    相关资源
    最近更新 更多