skip to Main Content

Currently a document looks like this:

  {
    "Post": "this is a post",
    "_id": ObjectId("630f3c32c1a580642a9ff4a0"),
    "iframe": ""https:/www.youtube.com/embed/RzVvThhjAKw"",
    "slug": "this-is-a-title",
    "title": "This is a title"
  }

But I want it like this:

{
    "Post": "this is a post",
    "_id": ObjectId("630f3c32c1a580642a9ff4a0"),
    "iframe": "https:/www.youtube.com/embed/RzVvThhjAKw",
    "slug": "this-is-a-title",
    "title": "This is a title"
  }

How to remove double quotes inside double quotes in iframe string field?

2

Answers


  1. For aggregate query, you can work with $regexFind to capture the match group.

    1. set – Set iframe field.

      1.1. $first – Get the first item of array from the result 1.1.1.

      1.1.1. $getField – Get the captures array field from the result of 1.1.1.1.

      1.1.1.1. $regexFind – Return a regex object result from matching the iframe value with provided regex expression.

    db.collection.aggregate([
      {
        $set: {
          iframe: {
            $first: {
              $getField: {
                field: "captures",
                input: {
                  $regexFind: {
                    input: "$iframe",
                    regex: ""([^"]+)""
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground


    You may use $ifNull operator to remain the existing iframe value if it doesn’t match the regex expression.

    db.collection.aggregate([
      {
        $set: {
          iframe: {
            $ifNull: [
              {
                $first: {
                  "$getField": {
                    "field": "captures",
                    "input": {
                      $regexFind: {
                        input: "$iframe",
                        regex: ""([^"]+)""
                      }
                    }
                  }
                }
              },
              "$iframe"
            ]
          }
        }
      }
    ])
    

    Demo with $ifNull @ Mongo Playground

    Login or Signup to reply.
  2. If you want update the document in the collection, here’s one way to do it.

    db.collection.update({
      "_id": ObjectId("630f3c32c1a580642a9ff4a0")
    },
    [
      {
        "$set": {
          "iframe": {
            "$replaceAll": {
              "input": "$iframe",
              // find every double quote ...
              "find": """,
              // ... and replace it with nothing
              "replacement": ""
            }
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search