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?
CodePudding user response:
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.
CodePudding user response:
For aggregate query, you can work with $regexFind
to capture the match group.
set
- Setiframe
field.1.1.
$first
- Get the first item of array from the result 1.1.1.1.1.1.
$getField
- Get thecaptures
array field from the result of 1.1.1.1.1.1.1.1.
$regexFind
- Return a regex object result from matching theiframe
value with provided regex expression.
db.collection.aggregate([
{
$set: {
iframe: {
$first: {
$getField: {
field: "captures",
input: {
$regexFind: {
input: "$iframe",
regex: "\"([^\"] )\""
}
}
}
}
}
}
}
])
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"
]
}
}
}
])