Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

aggregation framework - Copy first array value to another field in MongoDB

I have an old list of products that store the descriptions in an array at index [0]. The model is set up as a string. So my plan is to extract that value and add it to a temporary field. Step 2 would be to take that value and copy it to the original field. This is the 'wrong' product I want to fix.

{_id : 1 , pDescription : ['great product']},
{_id : 2 , pDescription : ['another product']}

All I want to is to change the array to a string like this:

{_id : 1 , pDescription : 'great product'},
{_id : 2 , pDescription : 'another product'}

I have tried this to create the temporary description:

    Products.aggregate([
    {
        $match: {
            pDescription: {
                $type: "array"
            }
        }
        },
    {
        $set: {
            pDescTemp: {
                $first: "$pDescription"
            }
        }
            }
        ]).exec((err, r) => {
       // do stuff here
   });

The command works fine without the $first command. The error reads: MongoError: Unrecognized expression '$first'

Any tips on how to fix this are appreciated! Thanks!

question from:https://stackoverflow.com/questions/65947153/copy-first-array-value-to-another-field-in-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe this is what you need to update your pDescription field to be equal to the first element of the array already stored as pDescription:

db.Products.updateMany({},
[
  {
    $set: {
      pDescription: {
        $arrayElemAt: [
          "$pDescription",
          0
        ]
      }
    }
  }
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...