📜  pymongo 将 json 添加到集合中 - Javascript (1)

📅  最后修改于: 2023-12-03 15:33:50.941000             🧑  作者: Mango

使用 PyMongo 将 JSON 添加到集合中 - JavaScript

PyMongo 是 MongoDB 的官方 Python 驱动程序之一,能够在 Python 中连接和操纵 MongoDB 数据库。本文将介绍如何使用 PyMongo 将 JSON 数据添加到 MongoDB 集合中。

步骤
  1. 安装 PyMongo

在终端中运行以下命令来安装 PyMongo:

pip install pymongo
  1. 连接 MongoDB

使用 PyMongo 连接到数据库,需要指定 MongoDB 服务器的地址和端口号,并且选择要使用的数据库:

const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost:27017';
const dbName = 'myDatabase';

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  const collection = client.db(dbName).collection('myCollection');
  // 在这里添加 JSON 数据到集合中
  client.close();
});
  1. 添加 JSON 数据到集合中

可以使用 insert_one() 方法将 JSON 对象添加到集合中:

const data = { name: 'John', age: 30, city: 'New York' };
collection.insertOne(data, (err, res) => {
  if (err) throw err;
  console.log('1 document inserted');
});

如果要添加多个 JSON 对象到集合中,可以使用 insert_many() 方法:

const data = [
  { name: 'John', age: 30, city: 'New York' },
  { name: 'Jane', age: 25, city: 'Los Angeles' },
  { name: 'Bob', age: 40, city: 'Chicago' }
];
collection.insertMany(data, (err, res) => {
  if (err) throw err;
  console.log(`${res.insertedCount} documents inserted`);
});
  1. 执行脚本

将以上代码保存为一个 JavaScript 文件,例如 app.js,使用以下命令执行脚本:

node app.js
结论

本文介绍了使用 PyMongo 将 JSON 数据添加到 MongoDB 集合中的步骤。要完成此操作,需要连接到 MongoDB 数据库,并使用 insert_one()insert_many() 方法添加 JSON 对象到集合中。