您的位置:宽带测速网 > 网络知识 > MongoDB的JSON数据如何存储与查询

MongoDB的JSON数据如何存储与查询

2025-06-22 12:43来源:互联网 [ ]

MongoDB是一种文档数据库,它以JSON格式存储数据。在MongoDB中,数据以文档的形式存储在集合中。每个文档是一个键值对的集合,类似于JSON对象。

存储JSON数据:要存储JSON数据到MongoDB中,首先需要连接到数据库,选择一个集合,并插入文档。以下是一个示例代码:

// 连接到数据库const MongoClient = require('mongodb').MongoClient;const url = 'mongodb://localhost:27017';MongoClient.connect(url, (err, client) => {if (err) throw err;// 选择数据库和集合const db = client.db('mydb');const collection = db.collection('mycollection');// 插入JSON数据const data = { name: 'John', age: 25, city: 'New York' };collection.insertOne(data, (err, result) => {if (err) throw err;console.log('Data inserted successfully');client.close();});});

查询JSON数据:要查询JSON数据,可以使用MongoDB的find()方法。以下是一个示例代码:

// 连接到数据库const MongoClient = require('mongodb').MongoClient;const url = 'mongodb://localhost:27017';MongoClient.connect(url, (err, client) => {if (err) throw err;// 选择数据库和集合const db = client.db('mydb');const collection = db.collection('mycollection');// 查询JSON数据collection.find({ city: 'New York' }).toArray((err, result) => {if (err) throw err;console.log(result);client.close();});});

以上代码会查询所有城市为"New York"的文档,并将结果打印出来。可以根据需要构建更复杂的查询条件来查询JSON数据。