Menu Docs
Página inicial do Docs
/ / /
Node.js

Referência rápida

Esta página mostra a sintaxe do driver para vários comandos do MongoDB e links para sua referência relacionada e documentação da API.

Você pode usar o driver Node.js para conectar e executar comandos para implantações hospedadas nos seguintes ambientes:

  • MongoDB Atlas: o serviço totalmente gerenciado para implantações MongoDB na nuvem

  • MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB

  • MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB

Para saber mais sobre como executar operações CRUD comuns na UI do Atlas para sistemas hospedados no MongoDB Atlas, consulte Criar, visualizar, atualizar e excluir documentos.

Comando
Sintaxe
Find a Document

Usage Example
await coll.findOne({ title: 'Hamlet' });
coll.find({ year: 2005 });
await coll.insertOne({ title: 'Jackie Robinson' });
await coll.insertMany([
{ title: 'Dangal', rating: 'Not Rated' },
{ title: 'The Boss Baby', rating: 'PG' }
]);
await coll.updateOne(
{ title: 'Amadeus' },
{ $set: { 'imdb.rating': 9.5 } }
);
await coll.updateMany(
{ year: 2001 },
{ $inc: { 'imdb.votes': 100 } }
);
Update Arrays in Documents

await coll.updateOne(
{ title: 'Cosmos' },
{ $push: { genres: 'Educational' } }
):
await coll.replaceOne(
{ name: 'Deli Llama', address: '2 Nassau St' },
{ name: 'Lord of the Wings', zipcode: 10001 }
);
await coll.deleteOne({ title: 'Congo' });
await coll.deleteMany({ title: { $regex: /^Shark.*/ } });
await coll.bulkWrite([
{
insertOne: {
document: {
title: 'A New Movie',
year: 2022
}
}
},
{
deleteMany: {
filter: { year: { $lt: 1970 } }
}
}
]);
coll.watch([ { $match: { year: { $gte: 2022 } } } ]);
Access Data from a Cursor Iteratively

const cursor = coll.find();
for await (const doc of cursor) {
console.dir(doc);
}
Access Data from a Cursor as an Array

const cursor = coll.find();
const results = await cursor.toArray();
await coll.countDocuments({ year: 2000 });
List the Distinct Documents or Field Values
await coll.distinct('year');
Limit the Number of Documents Retrieved

coll.find().limit(2);
Skip Retrieved Documents

coll.find({ title: { $regex: /^Rocky/} }, { skip: 2 });
Sort the Documents When Retrieving Them

coll.find().sort({ year: 1});
Project Document Fields When Retrieving Them

coll.find().project({ _id: 0, year: 1, imdb: 1 });
await coll.createIndex({ title: 1, year: -1 });
// only searches fields with text indexes
coll.find({ $text: { $search: 'zissou' } });
Install the Driver Dependency
package.json
"dependencies": {
"mongodb": "^5.7",
...
}

Voltar

Próximos passos

Próximo

NOVIDADES