C100DBA · Question #92
What is the equivalent command in MongoDB for the following SQL query? SELECT * FROM posts WHERE author like "%john%"
The correct answer is A. db.posts.find( { author: /John/ } ). Option A is correct because MongoDB uses JavaScript-style regular expressions for pattern matching - the syntax { field: /pattern/ } is the direct equivalent of SQL's LIKE '%pattern%', where the regex /John/ matches any string containing "John" (just as %john% matches any value w
Question
What is the equivalent command in MongoDB for the following SQL query? SELECT * FROM posts WHERE author like "%john%"
Options
- Adb.posts.find( { author: /John/ } )
- Bdb.posts.find( { author: /AjohnA/ > )
- Cdb.posts.find( { $like: {author: /John/} } )
- Ddb.posts.find( { author: {$like: /John/} } )
How the community answered
(33 responses)- A94% (31)
- C3% (1)
- D3% (1)
Explanation
Option A is correct because MongoDB uses JavaScript-style regular expressions for pattern matching - the syntax { field: /pattern/ } is the direct equivalent of SQL's LIKE '%pattern%', where the regex /John/ matches any string containing "John" (just as %john% matches any value with "john" anywhere inside it).
Option B has a syntax error (> instead of } closes the query) and wraps the term in A...A - not valid regex wildcard syntax. Options C and D both invent a $like operator that simply does not exist in MongoDB; MongoDB has no such keyword, making both structurally invalid.
Memory tip: Think "regex replaces LIKE" - wherever SQL uses %value%, MongoDB uses /value/ placed directly as the field's value, no extra operator needed.
Topics
Community Discussion
No community discussion yet for this question.