MongoDB结合 WEB服务

主要涉及:

  • 在Node.js中操作MongoDB
  • MongoDB数据库和web服务的实际项目

Node.js 中操作MongoDB

参考:

在服务端操作 MongoDB:https://docs.mongodb.com/drivers/ 在 Node.js 中操作
MongoDB : https://docs.mongodb.com/drivers/node/

步骤:

  1. 初始化项目文件夹 mkdir node-mongodb-demo
  2. npm init -y
  3. npm i mongodb
  4. 连接mongodb数据库,创建index.js进行引入连接
  5. node执行index.js node index.js

index.js

const {
    MongoClient } = require("mongodb");
// Connection URI
const uri =
  "mongo://127.0.0.1:27017";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
   
  try {
   
    // Connect the client to the server
    await client.connect();
    // Establish and verify connection
    await client.db("admin").command({
    ping: 1 });
    console.log("Connected successfully to server");
  } catch (err) {
   
    console.log('Connect failed')
  } finally {
   
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

run()

Node对 MongoDB 进行 CRUD

CRUD(创建,读取,更新,删除)操作使您可以处理存储在MongoDB中的数据。

创建文档
插入一个:

const pizzaDocument = {
   
  name: "Neapolitan pizza",
  shape: "round",
  toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ],
};
const result = await pizzaCollection.insertOne(pizzaDocument);
console.dir(result.insertedCount);

插入多个:

const pizzaDocuments = [
  {
    name: "Sicilian pizza", shape: "square" },
  {
    name: "New York pizza", shape: "round" },
  {
    name: "Grandma pizza", shape: "square" },
];
const result = pizzaCollection.insertMany(pizzaDocuments);
console.dir(result.insertedCount);

查询文档

const findResult = await orders.find({
   
  name: "Lemony Snicket",
  date: {
   
    $gte: new Date(new Date().setHours(00, 00, 00)),
    $lt: new Date(new Date().setHours(23, 59, 59)),
  },
});

删除文档

const doc = {
   
  pageViews: {
   
    $gt: 10,
    $lt: 32768
  }
};

// 删除符合条件的单个文档

const deleteResult = await collection.deleteOne(doc);
console.dir(deleteResult.deletedCount);

// 删除符合条件的多个文档

const deleteManyResult = await collection.deleteMany(doc);
console.dir(deleteManyResult.deletedCount);

修改文档
更新1个文档:

const filter = {
    _id: 465 };
// update the value of the 'z' field to 42
const updateDocument = {
   
   $set: {
   
      z: 42,
   },
};

// 更新多个

const result = await collection.updateOne(filter, updateDocument);

// 更新多个

const result = await collection.updateMany(filter, updateDocument);

替换文档:

const filter = {
    _id: 465 };
// replace the matched document with the replacement document
const replacementDocument = {
   
   z: 42,
};
const result = await collection.replaceOne(filter, replacementDocument);

index.js

const {
    MongoClient, ObjectID } = require('mongodb')
// ObjectID 在MongoDB中是一个类型,必须使用ObjectID包裹才能生效

const client = new MongoClient('mongodb://127.0.0.1:27017', {
   
  useUnifiedTopology: true
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值