Pull and addtoset at the same time with mongo

前端 未结 4 2028
别那么骄傲
别那么骄傲 2020-12-01 14:21

I have a collection which elements can be simplified to this:

{tags : [1, 5, 8]}

where there would be at least one element in array and all of t

4条回答
  •  离开以前
    2020-12-01 14:39

    Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.

    And coupled with improvements made to db.collection.update() in Mongo 4.2 that can accept an aggregation pipeline, allowing the update of a field based on its own value,

    We can manipulate and update an array in ways the language doesn't easily permit:

    // { "tags" : [ 1, 5, 8 ] }
    db.collection.updateMany(
      { tags: 1 },
      [{ $set:
        { "tags":
          { $function: {
              body: function(tags) { tags.push(2); return tags.filter(x => x != 1); },
              args: ["$tags"],
              lang: "js"
          }}
        }
      }]
    )
    // { "tags" : [ 5, 8, 2 ] }
    

    $function takes 3 parameters:

    • body, which is the function to apply, whose parameter is the array to modify. The function here simply consists in pushing 2 to the array and filtering out 1.
    • args, which contains the fields from the record that the body function takes as parameter. In our case, "$tag".
    • lang, which is the language in which the body function is written. Only js is currently available.

提交回复
热议问题