Skip to content
MongoDB

Insert & Find

Insert documents and query a collection.

By EZ4Code Team
insertfindcrud

Code

// Insert documents
db.users.insertOne({ name: "Alice", age: 30, roles: ["admin"] });
db.users.insertMany([
  { name: "Bob", age: 25, roles: ["user"] },
  { name: "Carol", age: 35, roles: ["user", "editor"] }
]);

// Find with projection and limit
db.users.find({ age: { $gte: 30 } }, { name: 1, _id: 0 }).limit(10);

// Count and findOne
db.users.countDocuments({ "roles": "user" });
db.users.findOne({ name: "Alice" });

// Pretty print
db.users.find().pretty();

Explanation

insertOne and insertMany add documents to a collection, auto-generating an _id if not provided. find returns a cursor filtered by a query document, with the second argument projecting which fields to return. countDocuments gives an accurate count, unlike the deprecated count.

More MongoDB Snippets