mongoDB pymongo 增加&查找

mongoDB 练习笔记

start time: [2017-1-20 | 12:16]

1、mac 安装 mongo

# 终端代码
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install"

brew update

2、运行mango server

# 终端代码
mkdir ~/db/
mongo —dbpath  ~/db/

3、插入数据

# python代码
from pymongo import MongoClient

client = MongoClient()

db = client.test

for i in range(1000):

    # 插入到restaurants表
db.restaurants.insert_one({"name{}".format(i): "street {}".format(1000-i)})

    # 插入到用户表
db.Users.insert_one({
    "姓名": "Melissa Ramsey",
    "年龄": "28",
    "性别": "girl",
    "地址": {
        "街道": "2640 Lyndon Street",
        "城市": "Wayne",
        "省份": "PA",
        "国家": "US",
    },
    '电话': "+1.6106863153",
})



# 插入到用户表,相对上一数据,增加了“男朋友”
db.Users.insert_one({
    "姓名": "Edward Fernandez",
    "年龄": "28",
    "性别": "girl",
    "地址": {
        "街道": "4623 Cambridge Court",
        "城市": "Fort Smith",
        "省份": "AR",
        "国家": "US",
    },
    '电话': "+1.4797858387",
    '男朋友': "Emery Jones",
  })

4、查询数据

4.1 普通查询
# python代码
for user in db.Users.find({'姓名': "Edward Fernandez"}):
    print(user)
4.2、条件查询
# python代码
for user in db.Users.find({'$or': [{'姓名': "Edward Fernandez"}, {'电话': "+1.6106863153"}]}):
    print(user)

5、数据修改

# python代码
new_user = db.Users.update_one(
    {'男朋友': "Katelynn Lange"},
    {"$set": {"男朋友": "Helen Roland"},
     "$set": {"电话": "+1.5402494614"}}
)

推荐阅读更多精彩内容