C100DBA · Question #123
Which of the following is a valid insert statement in mongodb? Select all valid.
Option C is the only valid MongoDB insert statement. db.collection.insert() accepts a single document object (or an array of documents) as its argument, making db.test.insert({x:2,y:"apple"}) the correct form. Why the others are wrong: A - .push() is not a collection method in Mo
Question
Which of the following is a valid insert statement in mongodb? Select all valid.
Options
- Adb.test.push({x:2,y:"apple"})
- Bdb.test.insert«"x":2, "y":"apple"})
- Cdb.test.insert({x:2,y:"apple"})
- Ddb.test.insert({x:2},{y:"apple"})
Explanation
Option C is the only valid MongoDB insert statement. db.collection.insert() accepts a single document object (or an array of documents) as its argument, making db.test.insert({x:2,y:"apple"}) the correct form.
Why the others are wrong:
- A -
.push()is not a collection method in MongoDB;$pushis an array update operator used inside update operations, not for inserting new documents. - B - Uses
«(a guillemet character) instead of(to open the function call, making it a syntax error that would fail immediately in the shell. - D -
insert()does not accept two separate document arguments to insert two records; to insert multiple documents you must pass them as an array:db.test.insert([{x:2},{y:"apple"}]). The second argument position is reserved for an options object (e.g.,{ordered: false}), not another document.
Memory tip: Think of insert() as a single slot - it takes one thing: either one document {} or one array []. If you want multiple documents, wrap them in square brackets.
Topics
Community Discussion
No community discussion yet for this question.