Search code examples
mongodbmongoosemongodb-querymongoose-schema

Update two fields in same document in MongoDB, where one field is simple update, other field is append to existing array


A document in my MongoDB Collection has two fields which are

  1. lastLongLat - [123.45,11.34] GeoJSON Point format
  2. multipleLongLat - [[12,45],[78,89],[12,54]] GeoJSON MultiPoint format

An array newLongLat from Http Request is in this format : newLongLat = [78.486671,17.385044]; multipleLongLat already has array of arrays. I need to update two fields as :

  1. update lastLongLat to newLongLat
  2. append newLongLat to existing data in multipleLongLat array at the end.

Document can be filtered by {"productId" : productId}. I am using Mongoose framework with NodeJS. Please mention an efficient way to perform this operation simultaneously? Thanks in advance.


Solution

  • Simple $set in an aggregation pipeline. You can simply treat the coordinates field as an inner field of an object.

    db.collection.update({
      "productId": "p1"
    },
    [
      {
        $set: {
          "lastLongLat": {
            type: "Point",
            coordinates: [
              78.486671,
              17.385044
            ]
          },
          "multipleLongLat.coordinates": {
            "$concatArrays": [
              "$multipleLongLat.coordinates",
              [
                [
                  78.486671,
                  17.385044
                ]
              ]
            ]
          }
        }
      }
    ])
    

    Mongo Playground