注册

使用MongoDB操作文档

使用MongoDB操作文档的完整攻略如下:

1. 安装MongoDB

首先,在自己的电脑或者服务器上安装MongoDB,在 MongoDB官网 上可以找到最新版本的安装包,根据操作系统不同选择相应的安装包进行下载和安装即可。

2. 启动MongoDB服务

安装完成后,启动MongoDB服务,命令如下:

mongod

命令执行后,可以通过浏览器访问本地的MongoDB服务,URL为:http://localhost:27017

3. 连接MongoDB

使用以下代码连接MongoDB:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
  • pymongo.MongoClient 类用来连接MongoDB服务。
  • mongodb://localhost:27017/ 是MongoDB服务的地址和端口号。
  • mydatabase 是MongoDB中的数据库名,如果不存在则会自动创建。

4. 创建集合

MongoDB中的集合类似于关系型数据库中的表,可以通过以下代码创建集合:

collection = db["mycollection"]
  • db["mycollection"] 创建一个名为 mycollection 的集合,如果不存在则会自动创建。

5. 插入文档

可以使用以下代码向集合中插入文档:

mydict = { "name": "John", "address": "Highway 37" }
x = collection.insert_one(mydict)
print(x.inserted_id)
  • insert_one() 方法用于向集合中插入单个文档。
  • 上述代码中,mydict 表示要插入的文档,inserted_id 是插入文档后返回的 ID。

6. 查询文档

可以使用以下代码查询集合中的文档:

for x in collection.find():
  print(x)
  • find() 方法用于查询集合中的文档。
  • 上述代码中,使用 for 循环打印查询结果中的每一个文档。

示例1

# 导入包
import pymongo

# 连接MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")

# 创建数据库
mydb = client["testdb"]

# 创建集合
mycol = mydb["testcol"]

# 插入单个文档
mydict = { "name": "Alice", "age": 18 }
x = mycol.insert_one(mydict)
print(x.inserted_id)

# 查询文档
for x in mycol.find():
  print(x)

示例2

# 导入包
import pymongo

# 连接MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")

# 创建数据库
mydb = client["testdb"]

# 创建集合
mycol = mydb["testcol"]

# 插入多个文档
mylist = [
  { "name": "John", "address": "Highway 37" },
  { "name": "Peter", "address": "Lowstreet 27" },
  { "name": "Amy", "address": "Apple st 652" },
  { "name": "Hannah", "address": "Mountain 21" },
  { "name": "Michael", "address": "Valley 345" },
  { "name": "Sandy", "address": "Ocean blvd 2" },
  { "name": "Betty", "address": "Green Grass 1" },
  { "name": "Richard", "address": "Sky st 331" },
  { "name": "Susan", "address": "One way 98" },
  { "name": "Vicky", "address": "Yellow Garden 2" },
  { "name": "Ben", "address": "Park Lane 38" },
  { "name": "William", "address": "Central st 954" },
  { "name": "Chuck", "address": "Main Road 989" },
  { "name": "Viola", "address": "Sideway 1633" }
]

x = mycol.insert_many(mylist)
print(x.inserted_ids)

# 查询文档
for x in mycol.find():
  print(x)

以上就是使用MongoDB操作文档的完整攻略,希望可以帮助到您。