Mongodb新增文档、查询文档、更新文档、删除文档
在MongoDB中,您可以使用MongoDB shell或者使用编程语言中的MongoDB驱动来执行以下操作:
- 新增文档(插入文档):
// 使用MongoDB shell
db.collection.insertOne({key: 'value'}) // 插入单个文档
db.collection.insertMany([{key1: 'value1'}, {key2: 'value2'}]) // 插入多个文档
// 使用Node.js MongoDB驱动
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const client = new MongoClient(url);
async function insertDocuments() {
try {
await client.connect();
console.log('Connected to server');
const db = client.db(dbName);
const collection = db.collection('collection');
const insertOneResult = await collection.insertOne({key: 'value'});
console.log('InsertOne Result:', insertOneResult.insertedId);
const insertManyResult = await collection.insertMany([{key1: 'value1'}, {key2: 'value2'}]);
console.log('InsertMany Result:', insertManyResult.insertedIds);
} finally {
await client.close();
}
}
insertDocuments().catch(console.error);
- 查询文档:
// 使用MongoDB shell
db.collection.find({key: 'value'})
// 使用Node.js MongoDB驱动
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const client = new MongoClient(url);
async function findDocuments() {
try {
await client.connect();
console.log('Connected to server');
const db = client.db(dbName);
const collection = db.collection('collection');
const query = {key: 'value'};
const docs = await collection.find(query).toArray();
console.log('Found Documents:', docs);
} finally {
await client.close();
}
}
findDocuments().catch(console.error);
- 更新文档:
// 使用MongoDB shell
db.collection.updateOne({key: 'value'}, {$set: {key: 'newValue'}}) // 更新单个文档
db.collection.updateMany({key: 'value'}, {$set: {key: 'newValue'}}) // 更新多个文档
// 使用Node.js MongoDB驱动
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
const client = new MongoClient(url);
评论已关闭