Warm tip: This article is reproduced from stackoverflow.com, please click
mongodb

Multiple search with replacement in mongodb?

发布于 2020-03-27 10:17:04

Database with the following structure:

_id:5d0fe110d7b8c01a4c633222
Category:"Stripveiling (Nederlands)"
Lot title:"Blake en Mortimer - S.O.S. Meteoren - 1e Druk HC 1959"
Seller name:"Stripsmagazijn"
Seller country:"Nederland"
Bids count:22
Winning bid:"€ 1.950"
Bid amount:"Closed"

I need to change the value of the "Winning bid" from "1.950" to "1950". There may be many meanings and they may be different, therefore $replaceOne() does not suit. Can someone help with this?

Questioner
kshnkvn
Viewed
103
Ravi Shankar Bharti 2019-07-03 22:00

Continuing with Answer from your last post.

I think you can use $split and $reduce in your $project stage with $out stage as the last stage of the pipeline to convert all such occurances in your db.

The idea is to split the string with "." and concat the array back to form a string but without ".", and after that you can continue with the normal process.

You are getting the error $out failed: { ok: 0.0, errmsg: "operation exceeded time limit", code: 50, codeName: "MaxTimeMSExpired" } because of the timeout, you can increase the default timeout using $maxTimeMS

db.collection_name.aggregate([
    {
        $project: {
            category : "$category",
            category_name : "$category_name",
            lot_title : "$lot_title",
            seller_name : "$seller_name",
            seller_country : "$seller_country",
            bid_count : "$bid_count",
            winning_bid : { 
                $toInt : {
                    $substr : [
                        {
                            $reduce : {
                                input : { $split : ["$winning_bid","."]}},
                                initialValue: "",
                                in: { $concat : ["$$value", "$$this"] }
                            }
                        },
                        2,
                        -1
                    ]
                }
            },
            bid_amount : "$bid_amount",
            lot_image : "$lot_image"
        }
    },{
        $out : "collection_name"
    }
]).maxTimeMS(100)

you can increase the timeout as per your needs.

I havent tested the code, it should work theoritically, but you get the idea, you can change the code to suit your need.