1

There are some basic conversions questions already.

As I'm new to MongoDB, need help for this specific conversion:

Last modification date is being saved as String("last_modification" : "/Date(1520430205000)/") data type in my document. I have to get only numeric(1520430205000) value from the field and convert it to long as well.

After conversion, the last modification value should be 1520430205000 as long data type.

1 Answer 1

1

You can use $trim to remove all the characters that are not representing digits and then run $toLong operator. Both operators are available in MongoDB 4.0 or newer. Try:

db.collection.aggregate([
    {
        $addFields: {
            last_modification: {
                $trim: {
                    input: "$last_modification",
                    chars: "/Date()"
                }
            }
        }
    },
    {
        $addFields: {
            last_modification: {
                $toLong: "$last_modification"
            }
        }
    },
    { $out: "collection" }
])

MongoDB Playground

EDIT: You can use $out to modify existing collection

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mickl, it worked. but it did not update the value in the collection. Could you please help for updating the value in the collection as well?
@DevkinandanChauhan modified my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.