akman
akman

Reputation: 121

mongoDB $set problem with using value of document's key/another fields value

I have a problem with update and set in mongoDB.(MongoDB shell version v4.2.6) I have a collection that contains documents like:

      {
        "_id": ObjectId("5ec6b069a8640000b1002012"),
        "name": "MS WINDOWS DSP 10 HOME 32-BIT ENG",
        "brand": "MICROSOFT",
        "date_added": NumberInt("1590079220"),
        "supplier": {
            "name": "dsfgdft",
            "product_id": "00-01-901-091"
        },
    ...
}

When i try to add a new field to all the documents in the collection, with the following command:

db.products.update({},{$set:{search_stems:"$name"}},{multi:true})

The documents do not get the value of the $name for the key search_stems it just adds $name as search_stems value

     {
        "_id": ObjectId("5ec6b069a8640000b1002012"),
        "name": "MS WINDOWS DSP 10 HOME 32-BIT ENG",
        "brand": "MICROSOFT",
        "date_added": NumberInt("1590079220"),
        "supplier": {
            "name": "dsfgdft",
            "product_id": "00-01-901-091"
        },
    ...
"search_stem":"$name"
}

what am i doing wrong?

I have read the following

Update MongoDB field using value of another field

but it is not getting the direct value of a field from document they use $concat after $set

Upvotes: 1

Views: 1057

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

Try below query which uses aggregation pipeline in .updateMany() :

db.products.updateMany({},[ { $set: { search_stems : "$name" } } ])

In aggregation we can refer to a field using $, So we're wrapping your update operation in an array [] to say it's an aggregation pipeline, Using $set operator which is an alias to $addFields in aggregation we're able to set search_stems field's value taken out from name field.

Aggregation in updates is introduced since 4.2, prior to that if you do search_stems:"$name" it means you're assigning string value $name to a field called search_stems. As a note you don't need use {multi:true} option with .update() instead use .updateMany().

Upvotes: 2

Related Questions