Insert a document into another document in MongoDB

I'm trying to add a document in another document.

enter image description here

I am trying to insert a new document with a timestamp as a key and light prox and temp as the content of that document into document sensor_collection.

It's logical that my code doesn't work, because I'm setting a new sensor_collection. Does anyone know how I can set a timestamp document in sensor_collection or is it adviced not to do it this way?

This is the code:

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())
                    ))));

Currently this code overrides the timestamp that's already in the db.

Upvotes: 2

Views: 2442

Answers (2)

In the Mongodb documentation I found this:

"To specify a <field> in an embedded document or in an array, use dot notation."

I used the $set operator. And I'm setting 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())
                    )));

This works. Gives:

enter image description here

Upvotes: 0

Ali Dehghani
Ali Dehghani

Reputation: 48123

If you want to append to an existing embedded collection, use $push instead of $set. The $push operator appends a specified value to an array. Something like this:

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())
                    ))));

For more details on mongo's update operators, check this out

Upvotes: 1

Related Questions