Python操作Mongodb

MongoDB

是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。

在高负载的情况下,添加更多的节点,可以保证服务器性能。

MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

1.创建连接

import pymongo

client = pymongo.MongoClient(‘mongodb://localhost:27017‘)
#或
#client = pymongo.MongoClient(‘localhost‘,‘27017‘)

2.连接数据库

#操作test数据库db_name = ‘test‘
db = client[db_name]

3.选择要操作的集合(表)

collection_set01 = db[‘set01‘]

下面就可以使用collection_set01进行增删改查操作了.

4.增删改查操作

‘‘‘

###################--插入文档--####################
save() vs insert()
mongodb的save和insert函数都可以向collection里插入数据,但两者是有两个区别
1.

save函数实际就是根据参数条件,调用了insert或update函数.如果想插入的数据对象存在,insert函数会报错,而save函数是改变原来的对象;如果想插入的对象不存在,那么它们执行相同的插入操作.这里可以用几个字来概括它们两的区别,即所谓"有则改之,无则加之".
2. insert可以一次性插入一个列表,而不用遍历,效率高, save则需要遍历列表,一个个插入.
‘‘‘

record_l = [
{‘_id‘:0,‘name‘: ‘zzzzz‘,‘age‘: -27,‘high‘: 176},
{‘_id‘:1,‘name‘: ‘zhangweijian‘,‘age‘: 27,‘high‘: 171},
{‘_id‘:2,‘name‘: ‘zhang‘,‘age‘: 26,‘high‘: 173},
{‘_id‘:3,‘name‘: ‘wei‘,‘age‘: 29,‘high‘: 180},
{‘_id‘:4,‘name‘: ‘weijian‘,‘age‘: 30,‘high‘: 158},
{‘_id‘:5,‘name‘: ‘zhangjian‘,‘age‘: 22,‘high‘: 179},
{‘_id‘:6,‘name‘: ‘zwj‘,‘age‘: 19,‘high‘: 166},
{‘_id‘:100,‘name‘: ‘zwj‘,‘age‘: 19,‘list‘:[2,3,5]},
{‘_id‘:101,‘name‘: ‘zwj‘,‘age‘: 19,‘list‘:[1,2,3,4,5,6,7]},
]
try:
    for record in record_l:
        collection_set01.save(record)
except pymongo.errors.DuplicateKeyError:
    print ‘record exists‘
except Exception as e:
    print e

####################--删除数据--####################
remove()
delete_one(self, filter, collation=None)
delete_many(self, filter, collation=None)
 >>> db.test.count({‘x‘: 1})
      3
      >>> result = db.test.delete_one({‘x‘: 1})
      >>> result.deleted_count
      1
      >>> db.test.count({‘x‘: 1})
      2

    :Parameters:
      - `filter`: A query that matches the document to delete.
      - `collation` (optional): An instance of
        :class:`~pymongo.collation.Collation`. This option is only supported
        on MongoDB 3.4 and above.

    :Returns:
      - An instance of :class:`~pymongo.results.DeleteResult`.
‘‘‘

newinsert1 = {‘_id‘:7,‘comment‘:‘test delete‘}
newinsert2 = {‘_id‘:8,‘comment‘:‘test delete‘}
newinsert3 = {‘_id‘:9,‘comment‘:‘test delete‘}
collection_set01.save(newinsert1)
collection_set01.save(newinsert2)
collection_set01.save(newinsert3)

remove_before = collection_set01.find()
print ‘delete before‘
for obj in remove_before:
    print obj

collection_set01.delete_many({‘_id‘:{‘$gt‘:6,‘$lt‘:100}})   #删除所有满足条件的文档,删除_id大于6,小于100
collection_set01.delete_one({‘_id‘:6})   #删除一条满足条件的文档,删除_id=6
#collection_set01.delete_many({}) #删除整个集合
remove_after = collection_set01.find()
print ‘delete after‘
for obj in remove_after:
    print obj

#输出结果delete before{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}{u‘high‘: 166, u‘age‘: 19, u‘_id‘: 6, u‘name‘: u‘zwj‘}{u‘comment‘: u‘test delete‘, u‘_id‘: 7}{u‘comment‘: u‘test delete‘, u‘_id‘: 8}{u‘comment‘: u‘test delete‘, u‘_id‘: 9}delete after{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}

‘‘‘
###################--更新数据--####################
replace_one(self, filter, replacement, upsert=False, bypass_document_validation=False, collation=None)
update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None)
update_many(self, filter, update, upsert=False, bypass_document_validation=False, collation=None)
‘‘‘

collection_set01.replace_one({‘_id‘: 1},{‘comment‘: ‘after replace_one operation just exists comment(key)‘})  #replace_one用指定的key-value替代原来所有的key-value
collection_set01.update_one({ "high" : { ‘$gt‘ : 170 } } , { ‘$set‘ : { "comment" : "更新于身高高于170的一条记录"}}) #update_one更新已经对应的key-value,其它不变
collection_set01.update_many({‘high‘:{‘$gt‘:171}},{‘$set‘:{‘comment‘:‘use update_many‘}})  #同上,能够update所有符合匹配条件的文档

‘‘‘
########################--查询--###################
find(self, filter=None, *args, **kwargs)
find_one(self, filter=None, *args, **kwargs)
params:projection/limit/skip
‘‘‘

 find方法源码

find(self, *args, **kwargs) method of pymongo.collection.Collection instance
    Query the database.

    The `filter` argument is a prototype document that all results
    must match. For example:

    >>> db.test.find({"hello": "world"})

    only matches documents that have a key "hello" with value
    "world".  Matches can have other keys *in addition* to
    "hello". The `projection` argument is used to specify a subset
    of fields that should be included in the result documents. By
    limiting results to a certain subset of fields you can cut
    down on network traffic and decoding time.
    Raises :class:`TypeError` if any of the arguments are of
    improper type. Returns an instance of
    :class:`~pymongo.cursor.Cursor` corresponding to this query.

    The :meth:`find` method obeys the :attr:`read_preference` of
    this :class:`Collection`.

    :Parameters:
      - `filter` (optional): a SON object specifying elements which
        must be present for a document to be included in the
        result set
      - `projection` (optional): a list of field names that should be
        returned in the result set or a dict specifying the fields
        to include or exclude. If `projection` is a list "_id" will
        always be returned. Use a dict to exclude fields from
        the result (e.g. projection={‘_id‘: False}).
      - `skip` (optional): the number of documents to omit (from
        the start of the result set) when returning the results
      - `limit` (optional): the maximum number of results to
        return
      - `no_cursor_timeout` (optional): if False (the default), any
        returned cursor is closed by the server after 10 minutes of
        inactivity. If set to True, the returned cursor will never
        time out on the server. Care should be taken to ensure that
        cursors with no_cursor_timeout turned on are properly closed.
      - `cursor_type` (optional): the type of cursor to return. The valid
        options are defined by :class:`~pymongo.cursor.CursorType`:

        - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
          this find call will return a standard cursor over the result set.
        - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
          find call will be a tailable cursor - tailable cursors are only
          for use with capped collections. They are not closed when the
          last data is retrieved but are kept open and the cursor location
          marks the final document position. If more data is received
          iteration of the cursor will continue from the last document
          received. For details, see the `tailable cursor documentation
          <http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_.
        - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
          of this find call will be a tailable cursor with the await flag
          set. The server will wait for a few seconds after returning the
          full result set so that it can capture and return additional data
          added during the query.
        - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
          find call will be an exhaust cursor. MongoDB will stream batched
          results to the client without waiting for the client to request
          each batch, reducing latency. See notes on compatibility below.

      - `sort` (optional): a list of (key, direction) pairs
        specifying the sort order for this query. See
        :meth:`~pymongo.cursor.Cursor.sort` for details.
      - `allow_partial_results` (optional): if True, mongos will return
        partial results if some shards are down instead of returning an
        error.
      - `oplog_replay` (optional): If True, set the oplogReplay query
        flag.
      - `modifiers` (optional): A dict specifying the MongoDB `query
        modifiers`_ that should be used for this query. For example::

          >>> db.test.find(modifiers={"$maxTimeMS": 500})

      - `batch_size` (optional): Limits the number of documents returned in
        a single batch.
      - `manipulate` (optional): **DEPRECATED** - If True (the default),
        apply any outgoing SON manipulators before returning.
      - `collation` (optional): An instance of
        :class:`~pymongo.collation.Collation`. This option is only supported
        on MongoDB 3.4 and above.

    .. note:: There are a number of caveats to using
      :attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type:

      - The `limit` option can not be used with an exhaust cursor.

      - Exhaust cursors are not supported by mongos and can not be
        used with a sharded cluster.

    The :meth:`find` method obeys the :attr:`read_preference` of
    this :class:`Collection`.

    :Parameters:
      - `filter` (optional): a SON object specifying elements which
        must be present for a document to be included in the
        result set
      - `projection` (optional): a list of field names that should be
        returned in the result set or a dict specifying the fields
        to include or exclude. If `projection` is a list "_id" will
        always be returned. Use a dict to exclude fields from
        the result (e.g. projection={‘_id‘: False}).
      - `skip` (optional): the number of documents to omit (from
        the start of the result set) when returning the results
      - `limit` (optional): the maximum number of results to
        return
      - `no_cursor_timeout` (optional): if False (the default), any
        returned cursor is closed by the server after 10 minutes of
        inactivity. If set to True, the returned cursor will never
        time out on the server. Care should be taken to ensure that
        cursors with no_cursor_timeout turned on are properly closed.
      - `cursor_type` (optional): the type of cursor to return. The valid
        options are defined by :class:`~pymongo.cursor.CursorType`:

        - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
          this find call will return a standard cursor over the result set.
        - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
          find call will be a tailable cursor - tailable cursors are only
          for use with capped collections. They are not closed when the
          last data is retrieved but are kept open and the cursor location
          marks the final document position. If more data is received
          iteration of the cursor will continue from the last document
          received. For details, see the `tailable cursor documentation
          <http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_.
        - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
          of this find call will be a tailable cursor with the await flag
          set. The server will wait for a few seconds after returning the
          full result set so that it can capture and return additional data
          added during the query.
        - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
          find call will be an exhaust cursor. MongoDB will stream batched
          results to the client without waiting for the client to request
          each batch, reducing latency. See notes on compatibility below.

      - `sort` (optional): a list of (key, direction) pairs
        specifying the sort order for this query. See
        :meth:`~pymongo.cursor.Cursor.sort` for details.
      - `allow_partial_results` (optional): if True, mongos will return
        partial results if some shards are down instead of returning an
        error.
      - `oplog_replay` (optional): If True, set the oplogReplay query
        flag.
      - `modifiers` (optional): A dict specifying the MongoDB `query
        modifiers`_ that should be used for this query. For example::

          >>> db.test.find(modifiers={"$maxTimeMS": 500})

      - `batch_size` (optional): Limits the number of documents returned in
        a single batch.
      - `manipulate` (optional): **DEPRECATED** - If True (the default),
        apply any outgoing SON manipulators before returning.
      - `collation` (optional): An instance of
        :class:`~pymongo.collation.Collation`. This option is only supported
        on MongoDB 3.4 and above.

#直接上代码

#1.查询身高小于180的文档
print ‘-------------身高小于180:‘
print type(collection_set01.find({‘high‘:{‘$lt‘:180}})) #<class ‘pymongo.cursor.Cursor‘>
for r in collection_set01.find({‘high‘:{‘$lt‘:180}}):
    print r
print type(collection_set01.find_one({‘high‘:{‘$lt‘:180}})) #<type ‘dict‘>
print ‘use find_one:‘,collection_set01.find_one({‘high‘:{‘$lt‘:180}})[‘high‘]
print ‘use find_one:‘,collection_set01.find_one({‘high‘:{‘$lt‘:180}})

#2.查询特定键(select key1,key2 from table;)
print ‘-------------查询特定键--------‘
print ‘-------------查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):‘
for r in collection_set01.find({‘high‘:{‘$gt‘:170}},projection=[‘high‘,‘age‘]):print r
print ‘\n‘
print ‘--------------skip参数用法‘
for r in collection_set01.find({‘high‘:{‘$gt‘:170}},[‘high‘,‘age‘],skip=1):print r #skip=1跳过第一个匹配到的文档
for r in collection_set01.find({‘high‘:{‘$gt‘:170}},[‘high‘,‘age‘]).skip(1):print r #skip=1跳过第一个匹配到的文档
print ‘\n‘
print ‘--------------limit参数用法‘
for r in collection_set01.find({‘high‘:{‘$gt‘:170}},[‘high‘,‘age‘],limit=1):print r #limit=2限制显示2条文档
print ‘\n‘
print ‘--------------用{}描述特定键‘
for r in collection_set01.find({‘high‘:{‘$gt‘:170}},{‘high‘:1,‘age‘:1,‘_id‘:False}):print r

print ‘---------------------多条件查询‘
print collection_set01.find_one({‘high‘:{‘$gt‘:10},‘age‘:{‘$lt‘:26,‘$gt‘:10}})

#3.$in
print ‘----------------IN‘
for r in collection_set01.find({"age":{"$in":[23, 26, 32]}}): print r  # select * from users where age in (23, 26, 32)
#for u in db.users.find({"age":{"$nin":(23, 26, 32)}}): print u # select * from users where age not in (23, 26, 32)

#4.count统计数目
print ‘----------------count‘
print collection_set01.find({"age":{"$gt":20}}).count() # select count(*) from set01 where age > 10

#5.$or
print ‘----------------条件或‘
print ‘大于等于29或者小于23‘
for r in collection_set01.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}): print r

#6.$exists,是否存在字段
print ‘------------exists‘
for r in collection_set01.find({‘age‘:{‘$exists‘:True}}):print ‘age exists‘,r # select * from 集合名 where exists 键1
for r in collection_set01.find({‘age‘:{‘$exists‘:False}}):print ‘age not exists‘,r # select * from 集合名 where not exists 键1

#7.正则表达式查询
print ‘正则表达式查询‘
#method 1
for r in collection_set01.find({‘name‘:{‘$regex‘:r‘.*wei.*‘}}):print r   #找出name字段中包含wei的文档
#method 2
import re
Regex = re.compile(r‘.*zhang.*‘,re.IGNORECASE)
for r in collection_set01.find({‘name‘:Regex}):print r   #找出name字段中包含wei的文档

#8.sort排序

print ‘--------------------使用sort排序(文档中没有排序的字段也会打印出来,表示最小)‘
#pymongo.ASCENDING      1
#pymongo.DESCENDING     -1
#sort([[],()]),[],()均可
print ‘--------------age 升序‘
for r in collection_set01.find().sort([["age",pymongo.ASCENDING]]):print r
print ‘--------------age 降序‘
for r in collection_set01.find().sort([("age",-1)]):print r
print ‘--------------age升序,high升序‘
for r in collection_set01.find().sort((("age",pymongo.ASCENDING),("high",pymongo.ASCENDING))):print r
print ‘--------------age升序,high降序‘
for r in collection_set01.find(sort=[("age",pymongo.ASCENDING),("high",pymongo.ASCENDING)]):print r

#9.$all判断数组属性是否包含全部条件,注意与$in区别

print ‘-------------$all‘
for r in collection_set01.find({‘list‘:{‘$all‘:[2,3,4]}}):print r
print ‘-------------$in‘
for r in collection_set01.find({‘list‘:{‘$in‘:[2,3,4]}}):print r

#10.$size匹配数组属性元素数量
print ‘-------------$size‘
print ‘-------------size=3‘
for r in collection_set01.find({‘list‘:{‘$size‘:3}}):print r
print ‘-------------size=7‘
for r in collection_set01.find({‘list‘:{‘$size‘:7}}):print r

#11.$unset和$set相反表示移除文档属性
print ‘-------------------$unset‘
print ‘---before‘
for r in collection_set01.find({‘name‘:‘weijian‘}):print r
collection_set01.update({‘name‘:‘weijian‘},{‘$unset‘:{‘age‘:1}})
print ‘---after‘
for r in collection_set01.find({‘name‘:‘weijian‘}):print r

#输出结果-------------查询测试------------------------身高小于180:<class ‘pymongo.cursor.Cursor‘>{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}<type ‘dict‘>use find_one: 173use find_one: {u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}-------------查询特定键---------------------查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):{u‘high‘: 173, u‘age‘: 26, u‘_id‘: 2}{u‘high‘: 180, u‘age‘: 29, u‘_id‘: 3}{u‘high‘: 179, u‘age‘: 22, u‘_id‘: 5}{u‘high‘: 176, u‘age‘: -27, u‘_id‘: 0}

--------------skip参数用法{u‘high‘: 180, u‘age‘: 29, u‘_id‘: 3}{u‘high‘: 179, u‘age‘: 22, u‘_id‘: 5}{u‘high‘: 176, u‘age‘: -27, u‘_id‘: 0}{u‘high‘: 180, u‘age‘: 29, u‘_id‘: 3}{u‘high‘: 179, u‘age‘: 22, u‘_id‘: 5}{u‘high‘: 176, u‘age‘: -27, u‘_id‘: 0}

--------------limit参数用法{u‘high‘: 173, u‘age‘: 26, u‘_id‘: 2}

--------------用{}描述特定键{u‘high‘: 173, u‘age‘: 26}{u‘high‘: 180, u‘age‘: 29}{u‘high‘: 179, u‘age‘: 22}{u‘high‘: 176, u‘age‘: -27}---------------------多条件查询{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}----------------IN{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}----------------count4----------------条件或大于等于29或者小于23{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}------------exists用法age exists {u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}age exists {u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}age exists {u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}age exists {u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}age exists {u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}age exists {u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}age exists {u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}age not exists {u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}正则表达式查询{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}--------------------使用sort排序(文档中没有排序的字段也会打印出来,表示最小)--------------age 升序{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}--------------age 降序{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}--------------age升序,high升序{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}--------------age升序,high降序{u‘comment‘: u‘after replace_one operation just exists comment(key)‘, u‘_id‘: 1}{u‘high‘: 176, u‘comment‘: u‘use update_many‘, u‘age‘: -27, u‘_id‘: 0, u‘name‘: u‘zzzzz‘}{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}{u‘high‘: 179, u‘comment‘: u‘use update_many‘, u‘age‘: 22, u‘_id‘: 5, u‘name‘: u‘zhangjian‘}{u‘high‘: 173, u‘comment‘: u‘use update_many‘, u‘age‘: 26, u‘_id‘: 2, u‘name‘: u‘zhang‘}{u‘high‘: 180, u‘comment‘: u‘use update_many‘, u‘age‘: 29, u‘_id‘: 3, u‘name‘: u‘wei‘}{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}-------------$all{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}-------------$in{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}-------------$size用法-------------size=3{u‘age‘: 19, u‘_id‘: 100, u‘list‘: [2, 3, 5], u‘name‘: u‘zwj‘}-------------size=7{u‘age‘: 19, u‘_id‘: 101, u‘list‘: [1, 2, 3, 4, 5, 6, 7], u‘name‘: u‘zwj‘}-------------------$unset用法---before{u‘high‘: 158, u‘age‘: 30, u‘_id‘: 4, u‘name‘: u‘weijian‘}---after{u‘high‘: 158, u‘_id‘: 4, u‘name‘: u‘weijian‘}
时间: 2024-10-12 18:43:54

Python操作Mongodb的相关文章

python 操作mongoDB数据库

网上关于python 操作mongoDB的相关文章相对不是很多,并且质量也不是很高!下面给出一个完整的 增删改查示例程序! #!/usr/bin/python # -*- coding: utf-8 -*- import pymongo import re connection = pymongo.MongoClient('10.38.164.80',27017) tdb = connection.test collection = tdb.article #插入数据 try: insert_d

Python 操作 mongodb 数据库

原文地址:https://serholiu.com/python-mongodb 这几天在学习Python Web开发,于 是做准备做一个博客来练练手,当然,只是练手的,博客界有WordPress这样的好玩意儿,何必还自己造车呢?决定使用Tornado这个框架,然后数 据库方面决定顺便熟悉一下MongoDB这样的非关系型数据库.Python让我觉得轻松,再和MongoDB搭配上,那感觉真是好. 下面就谈谈Python操作MongoDB的一些基本用法,先介绍一下MongoDB,这是现在风头正劲的N

python操作MongoDB部分翻译

python操作MongoDB http://api.mongodb.org/python/current/index.html This tutorial is intended as an introduction to working with MongoDB and PyMongo . Prerequisites[前提条件] Before we start, make sure that you have the PyMongo distribution installed . In t

Python删除mongodb数据库和用户,查看Python操作mongodb的方法

#!/usr/bin/env python #coding:utf-8 from pymongo import MongoClient client = MongoClient('192.168.6.243', 27017) db=client['admin'] db.authenticate('root','123456') #help(db) #查看python操作mongodb的方法 for i in range(2,900): try: db = client['s%s' % i] db

Fedora上使用Python操作MongoDB学习笔记

1. 创建Python虚拟环境 Fedora中已经安装有Python2和Python3,可执行文件的目录在/usr/bin/目录下,其中软连接为 python->python2 python2->python2.x python3->python3.x 接下来采用Python3来操作MongoDB,因此为不污染原有的系统环境,以及隔离此特定应用,采用Python虚拟环境的方式. 创建虚拟环境 语法 $ python3 -m venv /path/to/new/virtual/enviro

python操作MONGODB数据库,提取部分数据再存储

目标:从一个数据库中提取几个集合中的部分数据,组合起来一共一万条.几个集合,不足一千条数据的集合就全部提取,够一千条的就用一万减去不足一千的,再除以大于一千的集合个数,得到的值即为所需提取文档的个数.从每个集合中提取的数据存放到新的对应集合中,新集合名称为原先集合加"_col". 用到相关技术点: 操作MONGODB: 先通过IP和端口号连接到MONGODB所在的机器,得到一个MONGODB客户端对象,然后认证某个数据库的账号密码连接到该数据库,得到一个该数据库的对象.一个数据库下有很

python操作mongodb数据库

目录[-] conn = pymongo.Connection(host=“192.168.1.202”) # 连接指定IP的数据库 db.users.save(u) # 用 save 也可以插入 更新指定一条记录 更新多条记录 update() 有几个参数需要注意: remove() 用于删除单个或全部文档,删除后的文档无法恢复. 查询 age 小于 15 的 查询 name 等于 user8 的 获取查询的一个 select name, age from users where age =

Python操作MongoDB文档数据库

1.Pymongo 安装 安装pymongo: pip install pymongo PyMongo是驱动程序,使python程序能够使用Mongodb数据库,使用python编写而成: 2.Pymongo 方法 insert_one():插入一条记录: insert():插入多条记录: find_one():查询一条记录,不带任何参数返回第一条记录,带参数则按条件查找返回: find():查询多条记录,不带参数返回所有记录,带参数按条件查找返回: count():查看记录总数: create

Python操作MongoDB(PyMongo模块的使用)

学习笔记,用作数据库查询,原文参考 1 #!/usr/bin/env python 2 #coding:utf-8 3 # Author: --<qingfengkuyu> 4 # Purpose: MongoDB的使用 5 # Created: 2014/4/14 6 #32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位) 7 8 import pymongo 9 import datetime 10 import random 11 12 #