MongoDB concatenate strings from two fields into a third field

前端 未结 8 1420
逝去的感伤
逝去的感伤 2020-12-09 09:14

How do I concatenate values from two string fields and put it into a third one?

I\'ve tried this:

db.collection.update(
  { \"_id\": { $exists: true          


        
相关标签:
8条回答
  • 2020-12-09 10:19

    Building on the answer from @rebe100x, as suggested by @Jamby ...

    You can use $project, $concat and $out (or $merge) in an aggregation pipeline. https://docs.mongodb.org/v3.0/reference/operator/aggregation/project/ https://docs.mongodb.org/manual/reference/operator/aggregation/concat/ https://docs.mongodb.com/manual/reference/operator/aggregation/out/

    For example:

        db.collection.aggregate(
           [
              { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } },
              { $out: "collection" }
           ]
        )
    
    

    With MongoDB 4.2 . . .

    MongoDB 4.2 adds the $merge pipeline stage which offers selective replacement of documents within the collection, while $out would replace the entire collection. You also have the option of merging instead of replacing the target document.

        db.collection.aggregate(
           [
              { $project: { newfield: { $concat: [ "$field1", " - ", "$field2" ] } } },
              { $merge: { into: "collection", on: "_id", whenMatched: "merge", whenNotMatched: "discard" }
           ]
        )
    

    You should consider the trade-offs between performance, concurrency and consistency, when choosing between $merge and $out, since $out will atomically perform the collection replacement via a temporary collection and renaming.

    https://docs.mongodb.com/manual/reference/operator/aggregation/merge/ https://docs.mongodb.com/manual/reference/operator/aggregation/merge/#merge-out-comparison

    0 讨论(0)
  • 2020-12-09 10:20

    **

    in my case this $concat worked for me ...

    **

    db.collection.update( { "_id" : {"$exists":true} }, 
       [ { 
           "$set" : { 
                     "column_2" :  { "$concat" : ["$column_4","$column_3"] }
                    }
          }
       ]
    
    0 讨论(0)
提交回复
热议问题