2

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

在此处输入图像描述

我正在尝试将带有时间戳的新文档作为键和光代理和临时作为该文档的内容插入到 documentsensor_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())
                    ))));

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

4

2 回答 2

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 更新运算符的更多详细信息,请查看

于 2015-12-19T16:51:56.123 回答
0

Mongodb 文档中,我发现了这个:

“要<field>在嵌入文档或数组中指定 a,请使用点表示法。”

我使用了 $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())
                    )));

这行得通。给出:

在此处输入图像描述

于 2015-12-19T21:57:02.370 回答