0

I want to findOne and findOneAndUpdate an element of a nested Array at a given index with the Node.js MongoDB driver.

Here is an example of that the data could look like:

{
  "_id": "ObjectId('5d00e4ede5527164b6051797')",
  "timestamp": 1560339693539,
  "slices": [
    {
      "image": "/dev/shm/tmpBlecUn/S000008_P1.png",
      "data": 123,
      "force": 16012
    },
    {
      "image": "/dev/shm/tmpBlecUn/S000009_P1.png",
      "data": 345,
      "force": 15989
    },
    {
      "image": "/dev/shm/tmpBlecUn/S000010_P1.png",
      "data": 567,
      "force": 15870
    }
  ]
}

Now for example, I want to get or update the value of "force" in the "slices" array at a specific index position.

I can't seem to find the right query or method for doing this. I've got a shabby solution to get the right element, but the "data" field normally has lots of data and I don't want to always get the whole slices array (>10mb).

This is my garbage solution for getting the force value:

function get_IdPrintLayerForce(_id, layer, callback) {
    MongoClient.connect(conf.dbURL, {useNewUrlParser: true},
        function(err, client) {
          if (err) log.error(err);
          const db = client.db(conf.dbName);
          const collection = db.collection('print');
          collection.findOne({_id: id}, {projection: {slices: true}}, 
          function(err, res) {
            if (err) log.error(err);
            client.close();
            const force = res['slices'][layer-1];
            log.silly('Fetched specific layer force from print: ' + force);
            callback(force, err);
          });
        });
  }
PhilippF.
  • 1
  • 2
  • I want to be sure I understand what you need. The `layer` parameter that receives the function is the position of the element you are looking for and you want the query result to be the object in that position (+ 1) of the `slices` array, right? Would it be possible for the function to also receive the value of a field from that element (image, data or force)? – virgiliogm Jun 12 '19 at 13:02
  • @VirgilioGM Yes exactly, for the getting function I want the force value at the index position defined by the "layer" parameter. I also need a update function for that exact same field where I would also give the new value in addition to the layer. – PhilippF. Jun 12 '19 at 13:21
  • Possible duplicate of [MongoDB: How do I update a single subelement in an array, referenced by the index within the array?](https://stackoverflow.com/questions/11372065/mongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde) – Vikash_Singh Jun 12 '19 at 14:43
  • Also to get element at specific index use [$arrayElemAt](https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/) – Vikash_Singh Jun 12 '19 at 14:49

0 Answers0