2022-03-27

MongoDB - New alternative update syntax in Mongo 5

 db.runCommand({

   update: "collection_name",

   updates: [

       {

           q: {

               "field1": "value1",

               "field2": "value2",

           },

           u: {

               $set: {

                   "field3": "value3",

               },

               multi: false,

               upsert: false,

           }

       }

   ],

});


MongoDB - Filter documents where a given field is NOT an array

 db.collection.aggregate([

    {$match: {

         $expr: { $ne: [ {$isArray: "$field_to_check"}, true] }

    }}

]);   

MongoDB - Filter when the result of two AND conditions, is NOT true (not -> X and Y)

db.collection_name.find({

    $nor: [

        {$and: [

            {"field1": "value"},

            {"field2.subfield": "value"},

        ]}

    ]

});   

2022-03-07

MongoDB - Update all collection documents with a new copy of an existing field

 db.COLLECTION_NAME.update(

    {

        FIELD_1: ANY_VALUE, 

    },

    [

        {$set: {

            "NEW_FIELD_COPY": "$ORIGINAL_SOURCE_FIELD", 

        }},

    ],

    {

        multi: true, 

        upsert: false,

    }

);

2021-11-26

MongoDB - Update field value using another field's value

db.test1.update(

    {

        "filter_field": 1,

    },

    [

        {$set: {

            "target_field": "$source_field"

        }}

    ]

); 

2021-11-12

MongoDB - Project a value based on the existance of a field

 {$cond: {

    if: {$eq: [ {$ifNull: ["$FIELD_NAME", null]}, null ]},

    then: NumberInt(0),

    else: NumberInt(1) 

}},


2021-10-02

MongoDB Realm - GraphQL custom resolver specification for Mongo Atlas Search index highlight results

 "highlights_field_name": {

  "type": "array",

  "items": {

    "type": "object",

    "title": "highlights_title",

    "properties": {


      "path": {

        "type": "string"

      },


      "score": {

        "type": "number"

      },


      "texts": {

        "type": "array",

        "items": {

          "type": "object",

          "title": "piece_texts",


          "properties": {

            "value": {

              "type": "string"

            },

            "type": {

              "type": "string"

            }

          }


        }

      }


      

    }

  }

}