i have the following sample documents:
{_id: "1", value: " 1"}
{_id: "2", value: "2"}
{_id: "3", value: "3 "}
How can i run a mongdb find function that returns the documented with a value that contains a space? So in this case, it would return 1 because it has a space at the beginning, and 3 because it has a space at the end
CodePudding user response:
Use $regex operator with regex pattern:
(^\s. )|(. \s$)
(^\s.*) - Group (()) with starts with (^) whitespace (\s) match any character (.) with at least one occurrence.
| - Or.
(.*\s$) - Group (()) with match any character (.) with at least one occurrence ( ) at the end ($).
Sample Regex 101 and Test Data
db.collection.find({
value: {
$regex: "(^\\s. )|(. \\s$)"
}
})
