python 连接操作mongodb数据库

1、python连接mongodb需要引入 MongoClient包

在命令行执行 命令:pip install MongoClient

废话不多说,直接进入正题

 


#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from pymongo import MongoClient

client = MongoClient("mongodb://xxxxxxxxxmongbd连接字符串")
// 连接对应的testdb库
collection = database["testdb"]


#修改attributes字段下的一个属性
#cursor = collection.update({ "_id": "mongo_test", "attributes.typeId": "attr-isImported"},{'$set': { "attributes.$.free": ["lp11111"] } })



#把attributes修改为下面的attributes
cursor = collection.update({ "_id": "mongo_test"},{'$set': { "attributes": [
            {
                "typeId": "ebb2b817-33f3-45ac-8ce0-5eb4029fb149",
                "values": [],
                "free": [
                    "100",
                    "100"
                ]
            },
            {
                "typeId": "attr-rejectReason",
                "values": [],
                "free": [
                    ""
                ]
            }] } })





#查询docType是product的数量
#cursor = collection.find({"docType":"product"}).count()

#print cursor

#第三个参数设置为true,代表insertOrUpdate,即存在即更新,否则插入该数据
#第四个参数,该参数为true,则批量更新,为false,则更新一条
cursor = collection.query(query,{'id':1},False, True)

#从10-20获取docType是product的id
for x in collection.find({"docType":"product"},{'id':1}).skip(10).limit(20):
    print (x['id'])





 

你可能感兴趣的:(mongodb,python)