nosql_action

 

ps -aux  查当前端口占用

connecting to: test
> show dbs
local   0.078125GB
testphp 0.203125GB
> use testphp
switched to db testphp
> show collections;
col
system.indexes
> exit()
Tue May  2 17:14:49.378 ReferenceError: exit is not defined
> exit;
well@well:~$ netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:50916         localhost:27017         TIME_WAIT
tcp        0      0 well:ssh                192.168.95.251:49389    ESTABLISHED
tcp        0    240 well:ssh                192.168.95.251:59617    ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  3      [ ]         STREAM     CONNECTED     191853
unix  3      [ ]         STREAM     CONNECTED     43915
unix  3      [ ]         STREAM     CONNECTED     43914
unix  3      [ ]         STREAM     CONNECTED     191852
well@well:~$ ps
  PID TTY          TIME CMD
  936 pts/1    00:00:00 bash
  959 pts/1    00:00:00 ps
well@well:~$ ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18320  3216 ?        Ss+  09:05   0:00 /bin/bash
root        70  0.0  0.0  61388  3240 ?        Ss   09:06   0:00 /usr/sbin/sshd
root        73  0.0  0.0  95116  6016 ?        Ss   11:57   0:00 sshd: well [pri
well        84  0.0  0.0  95116  4092 ?        S    11:57   0:00 sshd: well@pts/
well        85  0.0  0.0  18192  3400 pts/0    Ss+  11:57   0:00 -bash
mongodb    878  0.0  0.2 546928 50000 ?        Sl   14:48   0:08 /usr/bin/mongod
root       924  0.0  0.0  95116  6172 ?        Ss   17:03   0:00 sshd: well [pri
well       935  0.0  0.0  95116  4100 ?        R    17:04   0:00 sshd: well@pts/
well       936  0.0  0.0  18180  3352 pts/1    Ss   17:04   0:00 -bash
well       960  0.0  0.0  15572  2060 pts/1    R+   17:16   0:00 ps -aux
well@well:~$

 

 

 

well@well:/$ service mongodb start
 * Starting database mongodb                                                             start-stop-daemon: unable to open pidfile '/var/run/mongodb/mongodb.pid' for writing (Permission denied)
                                                                                  [fail]
well@well:/$ sudo service start mongod 
start: unrecognized service
well@well:/$ sudo service mongodb start
 * Starting database mongodb                                                      [ OK ] 
well@well:/$ 

 

 

w

 

>>> collection.remove(testUpdate99)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'testUpdate99' is not defined
>>> collection.remove(testUpdate)
{u'connectionId': 5, u'ok': 1.0, u'err': None, u'n': 0}
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
>>> new_post = [{"author":"Mike","date":datetime.datetime(2009,11,12,11,14)},{"sth":"sth123"}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'datetime' is not defined
>>> from bson import *
>>> new_post = [{"author":"Mike","date":datetime.datetime(2009,11,12,11,14)},{"sth":"sth123"}]
>>> collection.save(new_post)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 2435, in save
    common.validate_is_document_type("to_save", to_save)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/common.py", line 407, in validate_is_document_type
    "collections.MutableMapping" % (option,))
TypeError: to_save must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
>>> collection.insert_many(new_post)
<pymongo.results.InsertManyResult object at 0x7fd24ac6d280>
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'_id': ObjectId('59032937f9323f04207f7668'), u'author': u'Mike'}
{u'_id': ObjectId('59032937f9323f04207f7669'), u'sth': u'sth123'}
>>> 

 

 

怎样筛选出仅有num(属性?节点)的object  ? 有哪些简洁的code的写法?有哪些高效的程序执行方法?

 

>>> for i in collection.find().sort('num', -1):
...     print i
... 
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
>>> tmp = collection.find_one({'num':123})
>>> tmp2 = tmp.copy()
>>> tmp['num']='num_str'
>>> collection.save(tmp)
ObjectId('590316a0f9323f04207f7665')
>>> for i in collection.find({'num':*}) 
  File "<stdin>", line 1
    for i in collection.find({'num':*}) 
                                    ^
SyntaxError: invalid syntax
>>> for i in collection.find({'num':*}) :
  File "<stdin>", line 1
    for i in collection.find({'num':*}) :
                                    ^
SyntaxError: invalid syntax
>>> for i in collection.find({type:'num'}): 
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
    exhaust)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 124, in send_message_with_response
    set_slave_okay, sock_info.is_mongos, use_find_cmd)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 291, in get_message
    spec, self.fields, self.codec_options)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 443, in query
    encoded = bson.BSON.encode(query, check_keys, opts)
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 976, in encode
    return cls(_dict_to_bson(document, check_keys, codec_options))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 758, in _dict_to_bson
    check_keys, opts))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 735, in _element_to_bson
    "key was %r" % (key,))
bson.errors.InvalidDocument: documents must have only string keys, key was <type 'type'>
>>> for i in collection.find({'type':'num'}):
...     print i
... 
>>> for i in collection.find({},{'num':2}):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a')}
{u'_id': ObjectId('590310cdf9323f04207f7661')}
{u'_id': ObjectId('590310eef9323f04207f7662')}
{u'_id': ObjectId('5903165df9323f04207f7663')}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': u'num_str'}
>>> for i in collection.find({},{'num':16}):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a')}
{u'_id': ObjectId('590310cdf9323f04207f7661')}
{u'_id': ObjectId('590310eef9323f04207f7662')}
{u'_id': ObjectId('5903165df9323f04207f7663')}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': u'num_str'}
>>> for i in collection.find({},{'num':1}):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a')}
{u'_id': ObjectId('590310cdf9323f04207f7661')}
{u'_id': ObjectId('590310eef9323f04207f7662')}
{u'_id': ObjectId('5903165df9323f04207f7663')}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': u'num_str'}
>>> for i in collection.find({},{'num':4}):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a')}
{u'_id': ObjectId('590310cdf9323f04207f7661')}
{u'_id': ObjectId('590310eef9323f04207f7662')}
{u'_id': ObjectId('5903165df9323f04207f7663')}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': u'num_str'}
>>> for i in collection.find({'num':{'gt:o'}}):
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
    exhaust)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 124, in send_message_with_response
    set_slave_okay, sock_info.is_mongos, use_find_cmd)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 291, in get_message
    spec, self.fields, self.codec_options)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 443, in query
    encoded = bson.BSON.encode(query, check_keys, opts)
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 976, in encode
    return cls(_dict_to_bson(document, check_keys, codec_options))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 758, in _dict_to_bson
    check_keys, opts))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 743, in _element_to_bson
    return _name_value_to_bson(name, value, check_keys, opts)
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 728, in _name_value_to_bson
    type(value))
bson.errors.InvalidDocument: cannot convert value of type <type 'set'> to bson
>>> for i in collection.find({'num':{'gt':o}}):
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'o' is not defined
>>> for i in collection.find({'num':{'$gt':o}}):
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'o' is not defined
>>> for i in collection.find({'num':{'gt':0}}):
...     print i
... 
>>> for i in collection.find({'num':{'$gt':0}}):
...     print i
... 
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
>>> colection.update(tmp,tmp2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'colection' is not defined
>>> collection.update(tmp,tmp2)
{u'updatedExisting': True, u'connectionId': 5, u'ok': 1.0, u'err': None, u'n': 1}
>>> for i in collection.find({}):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
>>> testUpdate = collection.find_one({'num',123})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 1102, in find_one
    for result in cursor.limit(-1):
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
    exhaust)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 124, in send_message_with_response
    set_slave_okay, sock_info.is_mongos, use_find_cmd)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 291, in get_message
    spec, self.fields, self.codec_options)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 443, in query
    encoded = bson.BSON.encode(query, check_keys, opts)
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 976, in encode
    return cls(_dict_to_bson(document, check_keys, codec_options))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 754, in _dict_to_bson
    check_keys, opts))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 728, in _name_value_to_bson
    type(value))
bson.errors.InvalidDocument: cannot convert value of type <type 'set'> to bson
>>> testUpdate = collection.find_one({'num','123'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 1102, in find_one
    for result in cursor.limit(-1):
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
    exhaust)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 124, in send_message_with_response
    set_slave_okay, sock_info.is_mongos, use_find_cmd)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 291, in get_message
    spec, self.fields, self.codec_options)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/message.py", line 443, in query
    encoded = bson.BSON.encode(query, check_keys, opts)
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 976, in encode
    return cls(_dict_to_bson(document, check_keys, codec_options))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 754, in _dict_to_bson
    check_keys, opts))
  File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 728, in _name_value_to_bson
    type(value))
bson.errors.InvalidDocument: cannot convert value of type <type 'set'> to bson
>>> testUpdate = collection.find_one({'num':'123'})
>>> testUpdate = collection.find_one({'num':123})
>>> testUpdate1 = testUpdate.copy()
>>> testUpdate['num'] = '123_str'
>>> collection.save(testUpdate)
ObjectId('590316a2f9323f04207f7666')
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': u'123_str'}
>>> collection.update(testUpdate,testUpdate1)
{u'updatedExisting': True, u'connectionId': 5, u'ok': 1.0, u'err': None, u'n': 1}
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
>>> 

 

 

 

 

collection – Collection level operations — PyMongo 3.4.0 documentation
http://api.mongodb.com/python/current/api/pymongo/collection.html

 

w

>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
>>> collection.count()
3
>>> collection.find({'name':'nw'}).count()
1
>>> collection.save({'name':'nw'})
ObjectId('5903165df9323f04207f7663')
>>> collection.find({'name':'nw'}).count()
2
>>> collection.save({'num':12'}
  File "<stdin>", line 1
    collection.save({'num':12'}
                              ^
SyntaxError: EOL while scanning string literal
>>> collection.save({'num':12'})
  File "<stdin>", line 1
    collection.save({'num':12'})
                               ^
SyntaxError: EOL while scanning string literal
>>> collection.save({'num':12})
ObjectId('5903169df9323f04207f7664')
>>> collection.save({'num':123})
ObjectId('590316a0f9323f04207f7665')
>>> collection.save({'num':123})
ObjectId('590316a2f9323f04207f7666')
>>> collection.save({'num':3})
ObjectId('590316a5f9323f04207f7667')
>>> collection.find().count()
8
>>> for i in collection.find():
... print i
  File "<stdin>", line 2
    print i
        ^
IndentationError: expected an indented block
>>> for i in collection.find():
... print i:
  File "<stdin>", line 2
    print i:
        ^
IndentationError: expected an indented block
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
>>> collection.find().sort('num')
<pymongo.cursor.Cursor object at 0x7fd24ac6efd0>
>>> collection.find().sort("num")
<pymongo.cursor.Cursor object at 0x7fd24ac031d0>
>>> collection.find().sort("num")
<pymongo.cursor.Cursor object at 0x7fd24b29a2d0>
>>> 
>>> collection.find().sort("num")
<pymongo.cursor.Cursor object at 0x7fd24ac6efd0>
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
>>> for i in collection.find().sort('num')
  File "<stdin>", line 1
    for i in collection.find().sort('num')
                                         ^
SyntaxError: invalid syntax
>>> for i in collection.find().sort('num'):
...     print i:
  File "<stdin>", line 2
    print i:
           ^
SyntaxError: invalid syntax
>>>     print i 
  File "<stdin>", line 1
    print i
    ^
IndentationError: unexpected indent
>>> for i in collection.find().sort('num'):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
>>> for i in collection.find().sort('num', pymongo.DESCENDING):
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pymongo' is not defined
>>> for i in collection.find().sort('num', pymongo.DESCENDING):
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pymongo' is not defined
>>> for i in collection.find().sort('num', 1):
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
>>> for i in collection.find().sort('num', -1):
...     print i
... 
{u'_id': ObjectId('590316a0f9323f04207f7665'), u'num': 123}
{u'_id': ObjectId('590316a2f9323f04207f7666'), u'num': 123}
{u'_id': ObjectId('5903169df9323f04207f7664'), u'num': 12}
{u'_id': ObjectId('590316a5f9323f04207f7667'), u'num': 3}
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
{u'_id': ObjectId('5903165df9323f04207f7663'), u'name': u'nw'}
>>> 

 

 

 

w

 

 

root@well:/# python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'w'
w
>>> print 1+4
5
>>> from pymongo import *
>>> client = MongoClient()
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
root@well:/# mongodb
bash: mongodb: command not found
root@well:/# mongo  
MongoDB shell version: 2.4.9
connecting to: test
> show dbs
local    0.078125GB
wellmg    0.203125GB
> use wellmg
switched to db wellmg
> db.col.find()
{ "_id" : ObjectId("5902f90762277deee7287c0a"), "well" : "www" }
> exit;
root@well:/# python 
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pymongo import *
>>> client = MongoClient()
>>> db = ckient.wellmg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ckient' is not defined
>>> db = client.wellmg
>>> collection  = db.col 
>>> wdic = {name:'nw'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
>>> wdic = {'name':'nw'}
>>> collection.insert(wdic)
ObjectId('590310cdf9323f04207f7661')
>>> wdicb = {'name':'nwb'}
>>> collection.save(wdicb)
ObjectId('590310eef9323f04207f7662')
>>> collection.find()
<pymongo.cursor.Cursor object at 0x7fd24ac6efd0>
>>> collection.find()[0]
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
>>> collection.find()[1]
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
>>> collection.find()[2]
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
>>> collection.find()[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 570, in __getitem__
    raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
>>> for i in collection.find()
  File "<stdin>", line 1
    for i in collection.find()
                             ^
SyntaxError: invalid syntax
>>> for i in collection.find() ""
  File "<stdin>", line 1
    for i in collection.find() ""
                                ^
SyntaxError: invalid syntax
>>> for i in collection.find() print i
  File "<stdin>", line 1
    for i in collection.find() print i
                                   ^
SyntaxError: invalid syntax
>>> for i in collection.find():       
... print i
  File "<stdin>", line 2
    print i
        ^
IndentationError: expected an indented block
>>> for i in collection.find():
...     print i
... 
{u'_id': ObjectId('5902f90762277deee7287c0a'), u'well': u'www'}
{u'_id': ObjectId('590310cdf9323f04207f7661'), u'name': u'nw'}
{u'_id': ObjectId('590310eef9323f04207f7662'), u'name': u'nwb'}
>>> 

 

 sudo apt install python-pip

 

ubuntu@VM-52-248-ubuntu:~/postgresql$ pip install psycopg2
The program 'pip' is currently not installed. You can install it by typing:
sudo apt install python-pip
ubuntu@VM-52-248-ubuntu:~/postgresql$ sudo apt install python-pip

 

 

root@well:/# python -m pip install --upgrade pip
Downloading/unpacking pip from https://pypi.python.org/packages/b6/ac/7015eb97dc749283ffdec1c3a88ddb8ae03b8fad0f0e611408f196358da3/pip-9.0.1-py2.py3-none-any.whl#md5=297dbd16ef53bcef0447d245815f5144
  Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB): 1.3MB downloaded
Installing collected packages: pip
  Found existing installation: pip 1.5.4
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
Successfully installed pip
Cleaning up...

 

 

python -m pip install –upgrade pip

C:\>python -m pip install --upgrade pip
Requirement already up-to-date: pip in c:\program files\anaconda2\lib\site-packages

C:\>

 

 

 sudo python -m pip install pymongo

C:\>python -m pip update
ERROR: unknown command "update"

C:\>python pip update
python: can't open file 'pip': [Errno 2] No such file or directory

C:\>python -m pip install pymongo
Collecting pymongo
  Downloading pymongo-3.4.0-cp27-none-win_amd64.whl (267kB)
    3% |¨€¨?                              | 10kB 1.1kB/s eta 0:03:58Exception:
Traceback (most recent call last):
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\commands\install.py", line 310, in
    wb.build(autobuilding=True)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\wheel.py", line 750, in build
    self.requirement_set.prepare_files(self.finder)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\req\req_set.py", line 370, in prep
    ignore_dependencies=self.ignore_dependencies))
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\req\req_set.py", line 587, in _pre
    session=self.session, hashes=hashes)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 810, in unpack_
    hashes=hashes
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 649, in unpack_
    hashes)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 871, in _downlo
    _download_url(resp, link, content_file, hashes)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 595, in _downlo
    hashes.check_against_chunks(downloaded_chunks)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\utils\hashes.py", line 46, in chec
    for chunk in chunks:
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 563, in written
    for chunk in chunks:
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\utils\ui.py", line 139, in iter
    for x in it:
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\download.py", line 552, in resp_re
    decode_content=False):
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\_vendor\requests\packages\urllib3\
    data = self.read(amt=amt, decode_content=decode_content)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\_vendor\requests\packages\urllib3\
    flush_decoder = True
  File "C:\Program Files\Anaconda2\lib\contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "C:\Program Files\Anaconda2\lib\site-packages\pip\_vendor\requests\packages\urllib3\
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

C:\>python --upgrade pip
Unknown option: --
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.

C:\>python -m pip install pymongo --upgrade pip
Collecting pymongo
  Downloading pymongo-3.4.0-cp27-none-win_amd64.whl (267kB)
    100% |¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€¨€
Collecting pip
  Using cached pip-9.0.1-py2.py3-none-any.whl
Installing collected packages: pymongo, pip
  Found existing installation: pip 8.1.2
    Uninstalling pip-8.1.2:
      Successfully uninstalled pip-8.1.2
Successfully installed pip-9.0.1 pymongo-3.4.0

C:\>

 

 

 

wuser@ubuntu:~$ python -m pip install pymongo
Collecting pymongo
  Downloading pymongo-3.4.0-cp27-cp27mu-manylinux1_x86_64.whl (362kB)
    100% |████████████████████████████████| 368kB 15kB/s 
Installing collected packages: pymongo
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/bson'
wuser@ubuntu:~$ sudo python -m pip install pymongo
The directory '/home/wuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/wuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pymongo
  Downloading pymongo-3.4.0-cp27-cp27mu-manylinux1_x86_64.whl (362kB)
    100% |████████████████████████████████| 368kB 17kB/s 
Installing collected packages: pymongo
Successfully installed pymongo-3.4.0
wuser@ubuntu:~$ 

 

 python -m pip install pymongo

root@well:/# python -m pip install pymongo
Downloading/unpacking pymongo
  Downloading pymongo-3.4.0.tar.gz (583kB): 583kB downloaded
  Running setup.py (path:/tmp/pip_build_root/pymongo/setup.py) egg_info for package pymongo
    
Installing collected packages: pymongo
  Running setup.py install for pymongo
    building 'bson._cbson' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c bson/_cbsonmodule.c -o build/temp.linux-x86_64-2.7/bson/_cbsonmodule.o
    bson/_cbsonmodule.c:23:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    /tmp/pip_build_root/pymongo/setup.py:284: UserWarning:
    ********************************************************************
    WARNING: The bson._cbson extension module could not
    be compiled. No C extensions are essential for PyMongo to run,
    although they do result in significant speed improvements.
    The output above this warning shows how the compilation failed.
    
    Please see the installation docs for solutions to build issues:
    
    http://api.mongodb.org/python/current/installation.html
    
    Here are some hints for popular operating systems:
    
    If you are seeing this message on Linux you probably need to
    install GCC and/or the Python development package for your
    version of Python.
    
    Debian and Ubuntu users should issue the following command:
    
        $ sudo apt-get install build-essential python-dev
    
    Users of Red Hat based distributions (RHEL, CentOS, Amazon Linux,
    Oracle Linux, Fedora, etc.) should issue the following command:
    
        $ sudo yum install gcc python-devel
    
    If you are seeing this message on Microsoft Windows please install
    PyMongo using the MS Windows installer for your version of Python,
    available on pypi here:
    
    http://pypi.python.org/pypi/pymongo/#downloads
    
    If you are seeing this message on OSX please read the documentation
    here:
    
    http://api.mongodb.org/python/current/installation.html#osx
    ********************************************************************
    
      "The output above "
    command 'x86_64-linux-gnu-gcc' failed with exit status 1
    building 'pymongo._cmessage' extension
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ibson -I/usr/include/python2.7 -c pymongo/_cmessagemodule.c -o build/temp.linux-x86_64-2.7/pymongo/_cmessagemodule.o
    pymongo/_cmessagemodule.c:23:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    /tmp/pip_build_root/pymongo/setup.py:284: UserWarning:
    ********************************************************************
    WARNING: The pymongo._cmessage extension module could not
    be compiled. No C extensions are essential for PyMongo to run,
    although they do result in significant speed improvements.
    The output above this warning shows how the compilation failed.
    
    Please see the installation docs for solutions to build issues:
    
    http://api.mongodb.org/python/current/installation.html
    
    Here are some hints for popular operating systems:
    
    If you are seeing this message on Linux you probably need to
    install GCC and/or the Python development package for your
    version of Python.
    
    Debian and Ubuntu users should issue the following command:
    
        $ sudo apt-get install build-essential python-dev
    
    Users of Red Hat based distributions (RHEL, CentOS, Amazon Linux,
    Oracle Linux, Fedora, etc.) should issue the following command:
    
        $ sudo yum install gcc python-devel
    
    If you are seeing this message on Microsoft Windows please install
    PyMongo using the MS Windows installer for your version of Python,
    available on pypi here:
    
    http://pypi.python.org/pypi/pymongo/#downloads
    
    If you are seeing this message on OSX please read the documentation
    here:
    
    http://api.mongodb.org/python/current/installation.html#osx
    ********************************************************************
    
      "The output above "
    command 'x86_64-linux-gnu-gcc' failed with exit status 1
    
Successfully installed pymongo
Cleaning up...
root@well:/# 

 

 

 

apt-get update

apt-get install mongodb

mongo

service mongodb start

 

 

exit  

root@well:/# apt-get install mongodb
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libboost-dev libboost-filesystem1.54.0 libboost-program-options1.54.0
  libboost-system1.54.0 libboost-thread1.54.0 libboost1.54-dev
  libgoogle-perftools4 libpcap0.8 libsnappy1 libtcmalloc-minimal4 libunwind8
  libv8-3.14.5 mongodb-clients mongodb-dev mongodb-server
Suggested packages:
  libboost-doc libboost1.54-doc libboost-atomic1.54-dev
  libboost-chrono1.54-dev libboost-context1.54-dev libboost-coroutine.54-dev
  libboost-date-time1.54-dev libboost-exception1.54-dev
  libboost-filesystem1.54-dev libboost-graph1.54-dev
  libboost-graph-parallel1.54-dev libboost-iostreams1.54-dev
  libboost-locale1.54-dev libboost-log.54-dev libboost-math1.54-dev
  libboost-mpi1.54-dev libboost-mpi-python1.54-dev
  libboost-program-options1.54-dev libboost-python1.54-dev
  libboost-random1.54-dev libboost-regex1.54-dev
  libboost-serialization1.54-dev libboost-signals1.54-dev
  libboost-system1.54-dev libboost-test1.54-dev libboost-thread1.54-dev
  libboost-timer1.54-dev libboost-wave1.54-dev libboost1.54-tools-dev
  libmpfrc++-dev libntl-dev
The following NEW packages will be installed:
  libboost-dev libboost-filesystem1.54.0 libboost-program-options1.54.0
  libboost-system1.54.0 libboost-thread1.54.0 libboost1.54-dev
  libgoogle-perftools4 libpcap0.8 libsnappy1 libtcmalloc-minimal4 libunwind8
  libv8-3.14.5 mongodb mongodb-clients mongodb-dev mongodb-server
0 upgraded, 16 newly installed, 0 to remove and 85 not upgraded.
Need to get 8994 kB/21.4 MB of archives.
After this operation, 218 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.ubuntu.com/ubuntu/ trusty-updates/main libboost1.54-dev amd64 1.54.0-4ubuntu3.1 [5682 kB]
Get:2 http://archive.ubuntu.com/ubuntu/ trusty/universe mongodb-server amd64 1:2.4.9-1ubuntu2 [3312 kB]
Fetched 2453 kB in 2min 44s (14.9 kB/s)                                        
Selecting previously unselected package libpcap0.8:amd64.
(Reading database ... 32686 files and directories currently installed.)
Preparing to unpack .../libpcap0.8_1.5.3-2_amd64.deb ...
Unpacking libpcap0.8:amd64 (1.5.3-2) ...
Selecting previously unselected package libboost-system1.54.0:amd64.
Preparing to unpack .../libboost-system1.54.0_1.54.0-4ubuntu3.1_amd64.deb ...
Unpacking libboost-system1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Selecting previously unselected package libboost-filesystem1.54.0:amd64.
Preparing to unpack .../libboost-filesystem1.54.0_1.54.0-4ubuntu3.1_amd64.deb ...
Unpacking libboost-filesystem1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Selecting previously unselected package libboost-program-options1.54.0:amd64.
Preparing to unpack .../libboost-program-options1.54.0_1.54.0-4ubuntu3.1_amd64.deb ...
Unpacking libboost-program-options1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Selecting previously unselected package libboost-thread1.54.0:amd64.
Preparing to unpack .../libboost-thread1.54.0_1.54.0-4ubuntu3.1_amd64.deb ...
Unpacking libboost-thread1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Selecting previously unselected package libunwind8.
Preparing to unpack .../libunwind8_1.1-2.2ubuntu3_amd64.deb ...
Unpacking libunwind8 (1.1-2.2ubuntu3) ...
Selecting previously unselected package libboost1.54-dev.
Preparing to unpack .../libboost1.54-dev_1.54.0-4ubuntu3.1_amd64.deb ...
Unpacking libboost1.54-dev (1.54.0-4ubuntu3.1) ...
Selecting previously unselected package libboost-dev.
Preparing to unpack .../libboost-dev_1.54.0.1ubuntu1_amd64.deb ...
Unpacking libboost-dev (1.54.0.1ubuntu1) ...
Selecting previously unselected package libtcmalloc-minimal4.
Preparing to unpack .../libtcmalloc-minimal4_2.1-2ubuntu1.1_amd64.deb ...
Unpacking libtcmalloc-minimal4 (2.1-2ubuntu1.1) ...
Selecting previously unselected package libgoogle-perftools4.
Preparing to unpack .../libgoogle-perftools4_2.1-2ubuntu1.1_amd64.deb ...
Unpacking libgoogle-perftools4 (2.1-2ubuntu1.1) ...
Selecting previously unselected package libv8-3.14.5.
Preparing to unpack .../libv8-3.14.5_3.14.5.8-5ubuntu2_amd64.deb ...
Unpacking libv8-3.14.5 (3.14.5.8-5ubuntu2) ...
Selecting previously unselected package mongodb-dev.
Preparing to unpack .../mongodb-dev_1%3a2.4.9-1ubuntu2_amd64.deb ...
Unpacking mongodb-dev (1:2.4.9-1ubuntu2) ...
Selecting previously unselected package libsnappy1.
Preparing to unpack .../libsnappy1_1.1.0-1ubuntu1_amd64.deb ...
Unpacking libsnappy1 (1.1.0-1ubuntu1) ...
Selecting previously unselected package mongodb-clients.
Preparing to unpack .../mongodb-clients_1%3a2.4.9-1ubuntu2_amd64.deb ...
Unpacking mongodb-clients (1:2.4.9-1ubuntu2) ...
Selecting previously unselected package mongodb-server.
Preparing to unpack .../mongodb-server_1%3a2.4.9-1ubuntu2_amd64.deb ...
Unpacking mongodb-server (1:2.4.9-1ubuntu2) ...
Selecting previously unselected package mongodb.
Preparing to unpack .../mongodb_1%3a2.4.9-1ubuntu2_amd64.deb ...
Unpacking mongodb (1:2.4.9-1ubuntu2) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Setting up libpcap0.8:amd64 (1.5.3-2) ...
Setting up libboost-system1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Setting up libboost-filesystem1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Setting up libboost-program-options1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Setting up libboost-thread1.54.0:amd64 (1.54.0-4ubuntu3.1) ...
Setting up libunwind8 (1.1-2.2ubuntu3) ...
Setting up libboost1.54-dev (1.54.0-4ubuntu3.1) ...
Setting up libboost-dev (1.54.0.1ubuntu1) ...
Setting up libtcmalloc-minimal4 (2.1-2ubuntu1.1) ...
Setting up libgoogle-perftools4 (2.1-2ubuntu1.1) ...
Setting up libv8-3.14.5 (3.14.5.8-5ubuntu2) ...
Setting up mongodb-dev (1:2.4.9-1ubuntu2) ...
Setting up libsnappy1 (1.1.0-1ubuntu1) ...
Setting up mongodb-clients (1:2.4.9-1ubuntu2) ...
Setting up mongodb-server (1:2.4.9-1ubuntu2) ...
Adding system user `mongodb' (UID 105) ...
Adding new user `mongodb' (UID 105) with group `nogroup' ...
Not creating home directory `/home/mongodb'.
Adding group `mongodb' (GID 109) ...
Done.
Adding user `mongodb' to group `mongodb' ...
Adding user mongodb to group mongodb
Done.
invoke-rc.d: policy-rc.d denied execution of start.
Processing triggers for ureadahead (0.100.0-16) ...
Setting up mongodb (1:2.4.9-1ubuntu2) ...
Processing triggers for libc-bin (2.19-0ubuntu6.6) ...
root@well:/# mongo
MongoDB shell version: 2.4.9
connecting to: test
Fri Apr 28 16:05:29.868 Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
exception: connect failed
root@well:/# cd /home/etc/project/nosqlmongo
root@well:/home/etc/project/nosqlmongo# ls
mongodb
root@well:/home/etc/project/nosqlmongo# cp -R ^C
root@well:/home/etc/project/nosqlmongo# mv mongodb  -R /home/etc/project/nosqlmongo/mongodb_NOUSing
mv: invalid option -- 'R'
Try 'mv --help' for more information.
root@well:/home/etc/project/nosqlmongo# mv mongodb   /home/etc/project/nosqlmongo/mongodb_NOUSing
root@well:/home/etc/project/nosqlmongo# ls
mongodb_NOUSing
root@well:/home/etc/project/nosqlmongo# cd -
/
root@well:/# mongo 
MongoDB shell version: 2.4.9
connecting to: test
Fri Apr 28 16:09:24.556 Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
exception: connect failed
root@well:/# service mongodb start
 * Starting database mongodb                                                      [ OK ] 
root@well:/# mongo
MongoDB shell version: 2.4.9
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
> show dbs
local    0.078125GB
> use wellmg
switched to db wellmg
> db.col.save({well:'www'})
> db.col.find(0
... )
{ "_id" : ObjectId("5902f90762277deee7287c0a"), "well" : "www" }
> db.col.find()
{ "_id" : ObjectId("5902f90762277deee7287c0a"), "well" : "www" }
> exit;
root@well:/# 

 

 

 

 

 

 

>db.COLLECTION_NAME.ensureIndex({KEY:1})

语法中 Key 值为你要创建的索引字段,1为指定按升序创建索引,如果你想按降序来创建索引指定为-1即可。
实例

>db.col.ensureIndex({"title":1})
>

ensureIndex() 方法中你也可以设置使用多个字段创建索引(关系型数据库中称作复合索引)。

>db.col.ensureIndex({"title":1,"description":-1})
>

ensureIndex() 接收可选参数,可选参数列表如下:
Parameter    Type    Description
background    Boolean    建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加 "background" 可选参数。 "background" 默认值为false。
unique    Boolean    建立的索引是否唯一。指定为true创建唯一索引。默认值为false.
name    string    索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。
dropDups    Boolean    在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.
sparse    Boolean    对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.
expireAfterSeconds    integer    指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
v    index version    索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights    document    索引权重值,数值在 199,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language    string    对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override    string    对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.
实例

在后台创建索引:

db.values.ensureIndex({open: 1, close: 1}, {background: true})

通过在创建索引时加background:true 的选项,让创建工作在后台执行

 

 

 

> db.col.find().skip(34).limit(3)
> db.col.find().skip(4).limit(3)
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("590218d868f02acbb4b8d4aa"), "new-Attr" : "wset" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
> db.col.find({title:{$type:2}})
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.save({likes:123})
WriteResult({ "nInserted" : 1 })
> db.col.find({title:{$type:2}})
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.save({likes:123,title:'wt'})
WriteResult({ "nInserted" : 1 })
> db.col.find({title:{$type:2}})
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("5902245868f02acbb4b8d4b8"), "likes" : 123, "title" : "wt" }
> db.col.find({title:{$type:2}}).sort(likes,-1)
2017-04-28T01:03:47.853+0800 ReferenceError: likes is not defined
> db.col.find({title:{$type:2}}).sort({likes,-1})
2017-04-28T01:04:06.038+0800 SyntaxError: Unexpected token ,
> db.col.find({title:{$type:2}}).sort({likes:-1})
{ "_id" : ObjectId("5902245868f02acbb4b8d4b8"), "likes" : 123, "title" : "wt" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.find({title:{$type:2}}).sort({likes:-1})
{ "_id" : ObjectId("5902245868f02acbb4b8d4b8"), "likes" : 123, "title" : "wt" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.find({title:{$type:2}}).sort({likes:1})
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5902245868f02acbb4b8d4b8"), "likes" : 123, "title" : "wt" }
>

 

 

 

 

 

> db.col.find({'likes':'$lt:124,$gt:99'})
> db.col.find({'likes':{'$lt:124,$gt:99'}})
2017-04-28T00:38:46.204+0800 SyntaxError: Unexpected token }
> db.col.find({likes:{'$lt:124,$gt:99'}})
2017-04-28T00:39:20.266+0800 SyntaxError: Unexpected token }
> db.col.find({likes:{$lt:124,$gt:99}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags        " : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
> db.col.find({'likes':{$lt:124,$gt:99}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags        " : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
> db.col.save({23:22})
WriteResult({ "nInserted" : 1 })
> db.col.save({23:2ee2})
2017-04-28T00:53:14.354+0800 SyntaxError: Unexpected token ILLEGAL
> db.col.save({23:4543})
WriteResult({ "nInserted" : 1 })
> db.col.save({2e3:4543})
WriteResult({ "nInserted" : 1 })
> db.col.save({2e3fds:4543})
2017-04-28T00:53:35.274+0800 SyntaxError: Unexpected token ILLEGAL
> db.col.save({2e3fds4:4543})
2017-04-28T00:53:44.457+0800 SyntaxError: Unexpected token ILLEGAL
> db.col.save({2e3:4543})
WriteResult({ "nInserted" : 1 })
> db.col.save({3e3:4543})
WriteResult({ "nInserted" : 1 })
> db.col.save({3f3:4543})
2017-04-28T00:54:23.896+0800 SyntaxError: Unexpected token ILLEGAL
> db.col.save({e3:4543})
WriteResult({ "nInserted" : 1 })
> db.col.save({e3:'MATH-e'})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW",         "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags        " : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("590218d868f02acbb4b8d4aa"), "new-Attr" : "wset" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
{ "_id" : ObjectId("59021aa968f02acbb4b8d4ae"), "likes" : 1233 }
{ "_id" : ObjectId("59021b7d68f02acbb4b8d4af"), "23" : 34 }
{ "_id" : ObjectId("590221f568f02acbb4b8d4b0"), "23" : 22 }
{ "_id" : ObjectId("5902220168f02acbb4b8d4b1"), "23" : 4543 }
{ "_id" : ObjectId("5902220868f02acbb4b8d4b2"), "2000" : 4543 }
{ "_id" : ObjectId("5902222168f02acbb4b8d4b3"), "2000" : 4543 }
{ "_id" : ObjectId("5902223268f02acbb4b8d4b4"), "3000" : 4543 }
{ "_id" : ObjectId("5902224868f02acbb4b8d4b5"), "e3" : 4543 }
{ "_id" : ObjectId("5902225a68f02acbb4b8d4b6"), "e3" : "MATH-e" }
>

 

 

 

> db.col.find({'likes':100})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.find({'likes':100},{'title':'twDOC'}})
2017-04-28T00:31:38.198+0800 SyntaxError: Unexpected token }
> db.col.find({{'likes':100},{'title':'twDOC'}})
2017-04-28T00:31:59.375+0800 SyntaxError: Unexpected token {
> db.col.find({'likes':100},{'title':'twDOC'})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC" }
> db.col.find({'likes':100,'title':'twDOC'})
> db.col.find({'likes':100,'title':'tWDOC'})
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.find($or:['likes':100,'title':'tWDOC'])
2017-04-28T00:33:46.213+0800 SyntaxError: Unexpected token :
> db.col.find($or:[{'likes':100},{'title':'tWDOC'}])
2017-04-28T00:34:04.657+0800 SyntaxError: Unexpected token :
> db.col.find({$or:[{'likes':100},{'title':'tWDOC'}]})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.find({'title':'tWDOC',{$or:[{'likes':100},{'title':'tWDOC'}]}})
2017-04-28T00:35:55.494+0800 SyntaxError: Unexpected token {
> db.col.find({'title':'tWDOC',$or:[{'likes':100},{'title':'tWDOC'}]})
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.find({'likes':'$lt:124,$gt:99'})
> db.col.find({'likes':{'$lt:124,$gt:99'}})
2017-04-28T00:38:46.204+0800 SyntaxError: Unexpected token }
> db.col.find({likes:{'$lt:124,$gt:99'}})
2017-04-28T00:39:20.266+0800 SyntaxError: Unexpected token }
> db.col.find({likes:{$lt:124,$gt:99}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
> db.col.find({'likes':{$lt:124,$gt:99}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
>

 

 

 

> db.col.find().pretty()
{
        "_id" : ObjectId("5901fb94b0c1b192e67adc78"),
        "title" : "tw-save-UPDATE-ObjectId"
}
{
        "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"),
        "title" : "tw-NEW2-all",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5901fc50b0c1b192e67adc7b"),
        "title" : "tw-NEW2-all",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"),
        "title" : "tWDOC",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100,
        "new_field" : "guess the design"
}
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("590218d868f02acbb4b8d4aa"), "new-Attr" : "wset" }
> db.col.save({'likes':123})
WriteResult({ "nInserted" : 1 })
> db.col.save({'likes':1233})
WriteResult({ "nInserted" : 1 })
> db.col.find('likes':'$lt 23').pretty()
2017-04-28T00:23:26.855+0800 SyntaxError: Unexpected token :
> db.col.find('likes':'{$lt:23}').pretty()
2017-04-28T00:23:46.691+0800 SyntaxError: Unexpected token :
> db.col.find('likes':{$lt:23}).pretty()
2017-04-28T00:24:07.976+0800 SyntaxError: Unexpected token :
> db.col.find({'likes':{$lt:23}}).pretty()
> db.col.find({'likes':{$lt:123}}).pretty()
{
        "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"),
        "title" : "tw-NEW2-all",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5901fc50b0c1b192e67adc7b"),
        "title" : "tw-NEW2-all",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"),
        "title" : "tWDOC",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100,
        "new_field" : "guess the design"
}
> db.col.find({'likes':{$lt:123}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.save({23:34})
WriteResult({ "nInserted" : 1 })
> db.col.find({'likes':{$lt:123}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
> db.col.find({'likes':{$lte:123}})
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("59021aa568f02acbb4b8d4ad"), "likes" : 123 }
>

 

 

 

 

 

w

> db.col.save({'new-Attr':'wset'})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
{ "_id" : ObjectId("590218d868f02acbb4b8d4aa"), "new-Attr" : "wset" }
> use wdbc
switched to db wdbc
> show dbs
admin  (empty)
dbwb   0.078GB
local  0.078GB
> use wdbc
switched to db wdbc
> db.col.save({'3',234})
2017-04-28T00:15:27.998+0800 SyntaxError: Unexpected token ,
> db.col.save({'3','234'})
2017-04-28T00:15:40.150+0800 SyntaxError: Unexpected token ,
> db.col.save({'w3','234'})
2017-04-28T00:15:57.228+0800 SyntaxError: Unexpected token ,
> db.col.save({23:234})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5902195068f02acbb4b8d4ab"), "23" : 234 }
> db.col.save({23:234})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5902195068f02acbb4b8d4ab"), "23" : 234 }
{ "_id" : ObjectId("5902196468f02acbb4b8d4ac"), "23" : 234 }
> db.col.remove()
2017-04-28T00:16:49.256+0800 remove needs a query at src/mongo/shell/collection.js:299
> db.col.remove({})
WriteResult({ "nRemoved" : 2 })
> db.col.find()
> db.col.find()
> show dbs
admin  (empty)
dbwb   0.078GB
local  0.078GB
wdbc   0.078GB
>

 

 

MongoDB 更新文档 | 菜鸟教程 http://www.runoob.com/mongodb/mongodb-update.html

只更新第一条记录:
db.col.update( { “count” : { $gt : 1 } } , { $set : { “test2” : “OK”} } );
全部更新:
db.col.update( { “count” : { $gt : 3 } } , { $set : { “test2” : “OK”} },false,true );
只添加第一条:
db.col.update( { “count” : { $gt : 4 } } , { $set : { “test5” : “OK”} },true,false );
全部添加加进去:
db.col.update( { “count” : { $gt : 5 } } , { $set : { “test5” : “OK”} },true,true );
全部更新:
db.col.update( { “count” : { $gt : 15 } } , { $inc : { “count” : 1} },false,true );
只更新第一条记录:
db.col.update( { “count” : { $gt : 10 } } , { $inc : { “count” : 1} },false,false );

 

guess the degsign  

对出现的新数据的“新键”可以不对历史数据“加键”

扩展性

> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.update({'count':{$gt:1}},{$set:{'test2-onlyOne':'only one'}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
> db.col.update({'title':'tWDOC'},{$set:{'new_field':'guess the design'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100, "new_field" : "guess the design" }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
>

 

 

> db.col.save( "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId")
2017-04-27T22:28:54.423+0800 SyntaxError: Unexpected token :
> db.col.save({"_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-save-UPDATE-ObjectId" }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
>

 

 

> db.col.save(documentW,'5901fb94b0c1b192e67adc78')
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description"                                             : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.update({'title':'tW-NEW'},{$set:{'title':'tw-NEW1'}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.update({'title':'tW'},{$set:{'title':'tw-NEW1'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-NEW1", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.update({'title':'tW'},{$set:{'title':'tw-NEW2-all'}},{multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-NEW1", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.update({'title':'tW'},{$set:{'title':'tw-NEW2-all'}},{multi:true},{upsert:true})
assert failed : Fourth argument must be empty when specifying upsert and multi with an object.
Error: assert failed : Fourth argument must be empty when specifying upsert and multi with an object.
    at Error (<anonymous>)
    at doassert (src/mongo/shell/assert.js:11:14)
    at assert (src/mongo/shell/assert.js:20:5)
    at DBCollection.update (src/mongo/shell/collection.js:376:9)
    at (shell):1:8
2017-04-27T22:23:37.593+0800 Error: assert failed : Fourth argument must be empty when specifying upsert and multi with an object. at src/mongo/shell/assert.js:13
> db.col.update({'title':'tW'},{$set:{'title':'tw-NEW2-all'}},{multi:false},{upsert:true})
assert failed : Fourth argument must be empty when specifying upsert and multi with an object.
Error: assert failed : Fourth argument must be empty when specifying upsert and multi with an object.
    at Error (<anonymous>)
    at doassert (src/mongo/shell/assert.js:11:14)
    at assert (src/mongo/shell/assert.js:20:5)
    at DBCollection.update (src/mongo/shell/collection.js:376:9)
    at (shell):1:8
2017-04-27T22:24:59.842+0800 Error: assert failed : Fourth argument must be empty when specifying upsert and multi with an object. at src/mongo/shell/assert.js:13
> db.col.update({'title':'tW'},{$set:{'title':'tw-NEW2-all'}},{upsert:true})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("5901ff607f11d64efeb3ae26")
})
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tw-NEW1", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" : "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tw-NEW2-all", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description" : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901ff607f11d64efeb3ae26"), "title" : "tw-NEW2-all" }
>

 

ObjectId(“5901fb94b0c1b192e67adc78”)  是什么?

> show dbs
admin  (empty)
dbw    0.078GB
local  0.078GB
> use dbw
switched to db dbw
> db.dropDatabase()
{ "dropped" : "dbw", "ok" : 1 }
> show dbs
admin  (empty)
local  0.078GB
> use dbwb
switched to db dbwb
> db.col.insert({title:'tW',description:'dW',by:'byW',url:'urlW',tags:['w0','w1'                                            ],likes:100})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.insert({title:'tW1',description:'dW1',by:'byW',url:'urlW',tags:['w0','w                                            1'],likes:100})
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> documentW={title:'tW',description:'dW',by:'byW',url:'urlW',tags:['w0','w1'],li                                            kes:100}
{
        "title" : "tW",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
> db.col.insert(documentW)
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.save(documentW)
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.save(documentW,123)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> db.col.save(documentW,'5901fb94b0c1b192e67adc78')
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
> documentW={title:'tWDOC',description:'dW',by:'byW',url:'urlW',tags:['w0','w1']                                            ,likes:100}
{
        "title" : "tWDOC",
        "description" : "dW",
        "by" : "byW",
        "url" : "urlW",
        "tags" : [
                "w0",
                "w1"
        ],
        "likes" : 100
}
> db.col.save(documentW,'5901fb94b0c1b192e67adc78')
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("5901fb94b0c1b192e67adc78"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fbbfb0c1b192e67adc79"), "title" : "tW1", "description" :                                             "dW1", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc1cb0c1b192e67adc7a"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fc50b0c1b192e67adc7b"), "title" : "tW", "description" :                                             "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
{ "_id" : ObjectId("5901fcb4b0c1b192e67adc7c"), "title" : "tWDOC", "description"                                             : "dW", "by" : "byW", "url" : "urlW", "tags" : [ "w0", "w1" ], "likes" : 100 }
>

 

 

apt-get update

apt-get install -y mongodb

service mongodb start

 

mongo mongodb mongod

 

Last login: Wed Apr 26 23:45:56 2017 from 218.18.215.149
ubuntu@VM-52-248-ubuntu:~$ apt-get update
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
ubuntu@VM-52-248-ubuntu:~$ sudo apt-get update
Hit:1 http://mirrors.tencentyun.com/ubuntu xenial InRelease
Hit:2 http://mirrors.tencentyun.com/ubuntu xenial-security InRelease
Hit:3 http://mirrors.tencentyun.com/ubuntu xenial-updates InRelease
Get:4 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease [17.6 kB]
Get:5 http://repo.mysql.com/apt/ubuntu xenial InRelease [16.7 kB]
Err:5 http://repo.mysql.com/apt/ubuntu xenial InRelease
  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
Ign:4 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease
Fetched 34.2 kB in 5s (6187 B/s)
Reading package lists... Done
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://repo.mysql.com/apt/ubuntu xenial InRelease: The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: GPG error: http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C
W: The repository 'http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/xenial/InRelease  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: Some index files failed to download. They have been ignored, or old ones used instead.
ubuntu@VM-52-248-ubuntu:~$ sudo apt-get install -y mongodb -org
E: Option -org: Configuration item specification must have an =<val>.
ubuntu@VM-52-248-ubuntu:~$ sudo apt-get install -y mongodb-org
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package mongodb-org
ubuntu@VM-52-248-ubuntu:~$ sudo apt-get install -y mongodb-org
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package mongodb-org
ubuntu@VM-52-248-ubuntu:~$ sudo apt-get update
Hit:1 http://mirrors.tencentyun.com/ubuntu xenial InRelease
Hit:2 http://mirrors.tencentyun.com/ubuntu xenial-security InRelease
Hit:3 http://mirrors.tencentyun.com/ubuntu xenial-updates InRelease
Get:4 http://repo.mysql.com/apt/ubuntu xenial InRelease [16.7 kB]
Get:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease [17.6 kB]
Ign:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease
Err:4 http://repo.mysql.com/apt/ubuntu xenial InRelease
  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
Fetched 34.2 kB in 3s (9715 B/s)
Reading package lists... Done
W: GPG error: http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C
W: The repository 'http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://repo.mysql.com/apt/ubuntu xenial InRelease: The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/xenial/InRelease  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: Some index files failed to download. They have been ignored, or old ones used instead.
ubuntu@VM-52-248-ubuntu:~$ try with --fix-missing
No command 'try' found, did you mean:
 Command 'tty' from package 'coreutils' (main)
 Command 'tr' from package 'coreutils' (main)
 Command 'pry' from package 'pry' (universe)
 Command 'trn' from package 'trn4' (multiverse)
 Command 'trn' from package 'trn' (multiverse)
 Command 'trs' from package 'konwert' (universe)
try: command not found
ubuntu@VM-52-248-ubuntu:~$ sudo try with --fix-missing
sudo: try: command not found
ubuntu@VM-52-248-ubuntu:~$ su
Password:
root@VM-52-248-ubuntu:/home/ubuntu# apt-get update
Hit:1 http://mirrors.tencentyun.com/ubuntu xenial InRelease
Hit:2 http://mirrors.tencentyun.com/ubuntu xenial-security InRelease
Hit:3 http://mirrors.tencentyun.com/ubuntu xenial-updates InRelease
Get:4 http://repo.mysql.com/apt/ubuntu xenial InRelease [16.7 kB]
Err:4 http://repo.mysql.com/apt/ubuntu xenial InRelease
  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
Get:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease [17.6 kB]
Ign:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease
Fetched 34.2 kB in 1s (21.4 kB/s)
Reading package lists... Done
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://repo.mysql.com/apt/ubuntu xenial InRelease: The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: GPG error: http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C
W: The repository 'http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/xenial/InRelease  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: Some index files failed to download. They have been ignored, or old ones used instead.
root@VM-52-248-ubuntu:/home/ubuntu# apt-get update
Hit:1 http://mirrors.tencentyun.com/ubuntu xenial InRelease
Hit:2 http://mirrors.tencentyun.com/ubuntu xenial-security InRelease
Hit:3 http://mirrors.tencentyun.com/ubuntu xenial-updates InRelease
Get:4 http://repo.mysql.com/apt/ubuntu xenial InRelease [16.7 kB]
Err:4 http://repo.mysql.com/apt/ubuntu xenial InRelease
  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
Get:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease [17.6 kB]
Ign:5 http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease
Fetched 34.2 kB in 10s (3282 B/s)
Reading package lists... Done
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://repo.mysql.com/apt/ubuntu xenial InRelease: The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: GPG error: http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4F4EA0AAE5267A6C
W: The repository 'http://ppa.launchpad.net/ondrej/mysql-5.7/ubuntu xenial InRelease' is not signed.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/xenial/InRelease  The following signatures were invalid: KEYEXPIRED 1487236823  KEYEXPIRED 1487236823  KEYEXPIRED 1487236823
W: Some index files failed to download. They have been ignored, or old ones used instead.
root@VM-52-248-ubuntu:/home/ubuntu# sudo apt-get install -y mongodb-org
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package mongodb-org
root@VM-52-248-ubuntu:/home/ubuntu# sudo apt-get install -y mongodb
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libboost-filesystem1.58.0 libboost-program-options1.58.0
  libboost-system1.58.0 libboost-thread1.58.0 libgoogle-perftools4
  libpcrecpp0v5 libsnappy1v5 libtcmalloc-minimal4 libunwind8 libv8-3.14.5
  libyaml-cpp0.5v5 mongodb-clients mongodb-server
The following NEW packages will be installed:
  libboost-filesystem1.58.0 libboost-program-options1.58.0
  libboost-system1.58.0 libboost-thread1.58.0 libgoogle-perftools4
  libpcrecpp0v5 libsnappy1v5 libtcmalloc-minimal4 libunwind8 libv8-3.14.5
  libyaml-cpp0.5v5 mongodb mongodb-clients mongodb-server
0 upgraded, 14 newly installed, 0 to remove and 164 not upgraded.
Need to get 58.0 MB of archives.
After this operation, 196 MB of additional disk space will be used.
Get:1 http://mirrors.tencentyun.com/ubuntu xenial/main amd64 libpcrecpp0v5 amd64 2:8.38-3.1 [15.2 kB]
Get:2 http://mirrors.tencentyun.com/ubuntu xenial-updates/main amd64 libboost-system1.58.0 amd64 1.58.0+dfsg-5ubuntu3.1 [9146 B]
Get:3 http://mirrors.tencentyun.com/ubuntu xenial-updates/main amd64 libboost-filesystem1.58.0 amd64 1.58.0+dfsg-5ubuntu3.1 [37.5 kB]
Get:4 http://mirrors.tencentyun.com/ubuntu xenial-updates/main amd64 libboost-program-options1.58.0 amd64 1.58.0+dfsg-5ubuntu3.1 [138 kB]
Get:5 http://mirrors.tencentyun.com/ubuntu xenial-updates/main amd64 libboost-thread1.58.0 amd64 1.58.0+dfsg-5ubuntu3.1 [47.0 kB]
Get:6 http://mirrors.tencentyun.com/ubuntu xenial/main amd64 libtcmalloc-minimal4 amd64 2.4-0ubuntu5 [105 kB]
Get:7 http://mirrors.tencentyun.com/ubuntu xenial/main amd64 libunwind8 amd64 1.1-4.1 [46.5 kB]
Get:8 http://mirrors.tencentyun.com/ubuntu xenial/main amd64 libgoogle-perftools4 amd64 2.4-0ubuntu5 [187 kB]
Get:9 http://mirrors.tencentyun.com/ubuntu xenial/universe amd64 libv8-3.14.5 amd64 3.14.5.8-5ubuntu2 [1189 kB]
Get:10 http://mirrors.tencentyun.com/ubuntu xenial/universe amd64 libyaml-cpp0.5v5 amd64 0.5.2-3 [158 kB]
Get:11 http://mirrors.tencentyun.com/ubuntu xenial/main amd64 libsnappy1v5 amd64 1.1.3-2 [16.0 kB]
Get:12 http://mirrors.tencentyun.com/ubuntu xenial/universe amd64 mongodb-clients amd64 1:2.6.10-0ubuntu1 [48.6 MB]
Get:13 http://mirrors.tencentyun.com/ubuntu xenial/universe amd64 mongodb-server amd64 1:2.6.10-0ubuntu1 [7425 kB]
Get:14 http://mirrors.tencentyun.com/ubuntu xenial/universe amd64 mongodb amd64 1:2.6.10-0ubuntu1 [5112 B]
Fetched 58.0 MB in 3s (16.6 MB/s)
Selecting previously unselected package libpcrecpp0v5:amd64.
(Reading database ... 66285 files and directories currently installed.)
Preparing to unpack .../libpcrecpp0v5_2%3a8.38-3.1_amd64.deb ...
Unpacking libpcrecpp0v5:amd64 (2:8.38-3.1) ...
Selecting previously unselected package libboost-system1.58.0:amd64.
Preparing to unpack .../libboost-system1.58.0_1.58.0+dfsg-5ubuntu3.1_amd64.deb ...
Unpacking libboost-system1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Selecting previously unselected package libboost-filesystem1.58.0:amd64.
Preparing to unpack .../libboost-filesystem1.58.0_1.58.0+dfsg-5ubuntu3.1_amd64.deb ...
Unpacking libboost-filesystem1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Selecting previously unselected package libboost-program-options1.58.0:amd64.
Preparing to unpack .../libboost-program-options1.58.0_1.58.0+dfsg-5ubuntu3.1_amd64.deb ...
Unpacking libboost-program-options1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Selecting previously unselected package libboost-thread1.58.0:amd64.
Preparing to unpack .../libboost-thread1.58.0_1.58.0+dfsg-5ubuntu3.1_amd64.deb ...
Unpacking libboost-thread1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Selecting previously unselected package libtcmalloc-minimal4.
Preparing to unpack .../libtcmalloc-minimal4_2.4-0ubuntu5_amd64.deb ...
Unpacking libtcmalloc-minimal4 (2.4-0ubuntu5) ...
Selecting previously unselected package libunwind8.
Preparing to unpack .../libunwind8_1.1-4.1_amd64.deb ...
Unpacking libunwind8 (1.1-4.1) ...
Selecting previously unselected package libgoogle-perftools4.
Preparing to unpack .../libgoogle-perftools4_2.4-0ubuntu5_amd64.deb ...
Unpacking libgoogle-perftools4 (2.4-0ubuntu5) ...
Selecting previously unselected package libv8-3.14.5.
Preparing to unpack .../libv8-3.14.5_3.14.5.8-5ubuntu2_amd64.deb ...
Unpacking libv8-3.14.5 (3.14.5.8-5ubuntu2) ...
Selecting previously unselected package libyaml-cpp0.5v5:amd64.
Preparing to unpack .../libyaml-cpp0.5v5_0.5.2-3_amd64.deb ...
Unpacking libyaml-cpp0.5v5:amd64 (0.5.2-3) ...
Selecting previously unselected package libsnappy1v5:amd64.
Preparing to unpack .../libsnappy1v5_1.1.3-2_amd64.deb ...
Unpacking libsnappy1v5:amd64 (1.1.3-2) ...
Selecting previously unselected package mongodb-clients.
Preparing to unpack .../mongodb-clients_1%3a2.6.10-0ubuntu1_amd64.deb ...
Unpacking mongodb-clients (1:2.6.10-0ubuntu1) ...
Selecting previously unselected package mongodb-server.
Preparing to unpack .../mongodb-server_1%3a2.6.10-0ubuntu1_amd64.deb ...
Unpacking mongodb-server (1:2.6.10-0ubuntu1) ...
Selecting previously unselected package mongodb.
Preparing to unpack .../mongodb_1%3a2.6.10-0ubuntu1_amd64.deb ...
Unpacking mongodb (1:2.6.10-0ubuntu1) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for systemd (229-4ubuntu10) ...
Processing triggers for ureadahead (0.100.0-19) ...
Setting up libpcrecpp0v5:amd64 (2:8.38-3.1) ...
Setting up libboost-system1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Setting up libboost-filesystem1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Setting up libboost-program-options1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Setting up libboost-thread1.58.0:amd64 (1.58.0+dfsg-5ubuntu3.1) ...
Setting up libtcmalloc-minimal4 (2.4-0ubuntu5) ...
Setting up libunwind8 (1.1-4.1) ...
Setting up libgoogle-perftools4 (2.4-0ubuntu5) ...
Setting up libv8-3.14.5 (3.14.5.8-5ubuntu2) ...
Setting up libyaml-cpp0.5v5:amd64 (0.5.2-3) ...
Setting up libsnappy1v5:amd64 (1.1.3-2) ...
Setting up mongodb-clients (1:2.6.10-0ubuntu1) ...
Setting up mongodb-server (1:2.6.10-0ubuntu1) ...
Adding system user `mongodb' (UID 112) ...
Adding new user `mongodb' (UID 112) with group `nogroup' ...
Not creating home directory `/var/lib/mongodb'.
Adding group `mongodb' (GID 119) ...
Done.
Adding user `mongodb' to group `mongodb' ...
Adding user mongodb to group mongodb
Done.
Setting up mongodb (1:2.6.10-0ubuntu1) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu10) ...
Processing triggers for ureadahead (0.100.0-19) ...
root@VM-52-248-ubuntu:/home/ubuntu# service mongod start
Failed to start mongod.service: Unit mongod.service not found.
root@VM-52-248-ubuntu:/home/ubuntu# mongod
mongod --help for help and startup options
2017-04-27T21:42:57.922+0800 [initandlisten] MongoDB starting : pid=9053 port=27017 dbpath=/data/db 64-bit host=VM-52-248-ubuntu
2017-04-27T21:42:57.923+0800 [initandlisten] db version v2.6.10
2017-04-27T21:42:57.923+0800 [initandlisten] git version: nogitversion
2017-04-27T21:42:57.923+0800 [initandlisten] OpenSSL version: OpenSSL 1.0.2g  1 Mar 2016
2017-04-27T21:42:57.923+0800 [initandlisten] build info: Linux lgw01-12 3.19.0-25-generic #26~14.04.1-Ubuntu SMP Fri Jul 24 21:16:20 UTC 2015 x86_64 BOOST_LIB_VERSION=1_58
2017-04-27T21:42:57.923+0800 [initandlisten] allocator: tcmalloc
2017-04-27T21:42:57.923+0800 [initandlisten] options: {}
2017-04-27T21:42:57.929+0800 [initandlisten] exception in initAndListen: 10296
*********************************************************************
 ERROR: dbpath (/data/db) does not exist.
 Create this directory or give existing directory in --dbpath.
 See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
2017-04-27T21:42:57.929+0800 [initandlisten] dbexit:
2017-04-27T21:42:57.929+0800 [initandlisten] shutdown: going to close listening sockets...
2017-04-27T21:42:57.929+0800 [initandlisten] shutdown: going to flush diaglog...
2017-04-27T21:42:57.929+0800 [initandlisten] shutdown: going to close sockets...
2017-04-27T21:42:57.929+0800 [initandlisten] shutdown: waiting for fs preallocator...
2017-04-27T21:42:57.930+0800 [initandlisten] shutdown: lock for final commit...
2017-04-27T21:42:57.930+0800 [initandlisten] shutdown: final commit...
2017-04-27T21:42:57.930+0800 [initandlisten] shutdown: closing all files...
2017-04-27T21:42:57.930+0800 [initandlisten] closeAllFiles() finished
2017-04-27T21:42:57.930+0800 [initandlisten] dbexit: really exiting now
root@VM-52-248-ubuntu:/home/ubuntu# service mongod start
Failed to start mongod.service: Unit mongod.service not found.
root@VM-52-248-ubuntu:/home/ubuntu# service mongodb start
root@VM-52-248-ubuntu:/home/ubuntu# show dbs
The program 'show' can be found in the following packages:
 * mailutils-mh
 * nmh
Try: apt install <selected package>
root@VM-52-248-ubuntu:/home/ubuntu# mongo
MongoDB shell version: 2.6.10
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
> show dbs
admin  (empty)
local  0.078GB
> use local
switched to db local
> db.local.find().pretty()
> local..col.find().pretty()
2017-04-27T21:49:24.894+0800 SyntaxError: Unexpected token .
> local.col.find().pretty()
2017-04-27T21:49:33.874+0800 ReferenceError: local is not defined
> db.local.find().pretty()
> ;
> use dbw
switched to db dbw
> show dbs
admin  (empty)
local  0.078GB
> show dbs
admin  (empty)
local  0.078GB
> db.dbw.insert({"namew":"helloworldw"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin  (empty)
dbw    0.078GB
local  0.078GB
> show tables;
dbw
system.indexes
>

 

 

 

 

sudo apt-get install mongodb

 

 

Most Unix-like operating systems limit the system resources that a session may use. These limits may negatively impact MongoDB operation. See UNIX ulimit Settings for more information.

 

 

 

w

 

Install MongoDB Community Edition on Ubuntu — MongoDB Manual 3.4
https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu

Linux 平台安装 MongoDB | 菜鸟教程
http://www.runoob.com/mongodb/mongodb-linux-install.html

 

curl 

well@well:/home/etc/project$ ls
centossave  centossaveb
well@well:/home/etc/project$ mkdir nosqlmongo
well@well:/home/etc/project$ cd  nosqlmongo
well@well:/home/etc/project/nosqlmongo$ cd ..
well@well:/home/etc/project$ ll
total 0
drwxr-xr-x. 5 well well 61 Apr 27 18:43 ./
drwxr-xr-x. 1 well well 21 Apr 18 04:09 ../
drwxrwxr-x. 4 well well 36 Apr 25 23:31 centossave/
drwxrwxr-x. 4 well well 36 Apr 26 00:32 centossaveb/
drwxrwxr-x. 2 well well  6 Apr 27 18:43 nosqlmongo/
well@well:/home/etc/project$ cd - 
/home/etc/project/nosqlmongo
well@well:/home/etc/project/nosqlmongo$ ls
well@well:/home/etc/project/nosqlmongo$ curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz   
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

 

 

 

 

redis 命令

权限认证

数据类型:列表list 集合set

 

 

[root@hadoop3 ~]# redis-cli
127.0.0.1:6379> RANDOMKEY
(error) NOAUTH Authentication required.
127.0.0.1:6379> RANDOMKEY
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth(mypwd)
(error) ERR unknown command ‘auth(mypwd)’
127.0.0.1:6379> AUTH mypwd
OK
127.0.0.1:6379> RANDOWKEY
(error) ERR unknown command ‘RANDOWKEY’
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> LPUSH mtmp we
(integer) 1
127.0.0.1:6379> LPUSH mtmp we1
(integer) 2
127.0.0.1:6379> LPUSH mtmp we2
(integer) 3
127.0.0.1:6379> LPUSH mtmp we3
(integer) 4
127.0.0.1:6379> RANDOMKEY
“mtmp”
127.0.0.1:6379> RANDOMKEY
“mtmp”
127.0.0.1:6379> RANDOMKEY
“mtmp”
127.0.0.1:6379> RANDOMKEY
“mtmp”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“mtmp”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_old”
127.0.0.1:6379> RANDOMKEY
“http://www.tz1288.com/_new”
127.0.0.1:6379> SADD mtmp1 u0
(integer) 1
127.0.0.1:6379> SADD mtmp1 u1
(integer) 1
127.0.0.1:6379> SADD mtmp1 u0
(integer) 0
127.0.0.1:6379> LPUSH mtmp we
(integer) 5
127.0.0.1:6379> LPUSH mtmp we
(integer) 6
127.0.0.1:6379> SADD mtmp u0
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> SADD mtmp1 u0
(integer) 0
127.0.0.1:6379> SADD mtmp1 u02
(integer) 1
127.0.0.1:6379>

 

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。

Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

 

删除key

127.0.0.1:6379> del mtmp1

 

pymongo 的增删 更新  模糊匹配

 

 

from pymongo import *
import time, logging, os

start_time = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
os_sep = os.sep
this_file_abspath, this_file_name = os.path.dirname(os.path.abspath(__file__)), os.path.abspath(__file__).split(os_sep)[
    -1]
logf = time.strftime('%Y%m%d', time.localtime(time.time())) + this_file_name + '.log'
try:
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s[thread:%(thread)d][process:%(process)d]',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename=logf,
                        filemode='a')
except Exception as e:
    s = '%s%s%s' % ('logging.basicConfig EXCEPTION ', time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())), e)
    with open(logf, 'a') as fo:
        fo.write(s)
        os._exit(4002)
logging.info('START')

'''
字段构成
stdClass Object ( [_id] => MongoDB\BSON\ObjectID Object ( [oid] => 59b73dbd930c17474ff3959a ) [address] => www.ailaba.org/sell/184481750757937.html [pv] => 64 [expire_time] => 1513647257 

=> 大马力车用柴油机油、山东润滑油厂家哪家好、柴油机油-爱喇叭网 [unit_id] => 16180 [uid] => 50003510 [status] => 0 ) ===》 0 ,可能缺失,投放中---- unit_id 物料id ''' db = 'direct_vote_resource' mongo_k_l = ['10.10.10.152', 'admin', '123', db] # inner mongo_k_l[0] = '{}{}{}'.format('mongodb://', mongo_k_l[0], ':27017/') is_test = True is_test = False if is_test: mongo_k_l = ['192.168.35.90', 'admin', 'admin', db] def gen_mongo_client_db(db_=db): ''' 避免连接超时 注意socket污染 :param db_: :return: ''' h, u, p, db = mongo_k_l myclient = MongoClient(host=h, username=u, password=p, authMechanism='SCRAM-SHA-1') return myclient[db_] def select_to_dic(k, collection_name, database=gen_mongo_client_db(), filter={}, fields={}): ''' :param k: dict[k] :param collection_name: :param database: :param filter: :param fields: :return: dict ''' collection, r = database[collection_name], {} if fields == {}: cursor = collection.find(filter) else: cursor = collection.find(filter, fields) try: c = 0 for doc in cursor: r[doc[k]] = doc c += 1 if c > 10: break finally: cursor.close() return r collection_name = 'kwaddress' ''' TODO 2018年5月22日 10:47:18 expire_time 0,1字段含义不明,假定其他值为合法时间戳,mogo数据不断更新中 ''' def chk(res_dic_k='address', fields_d={'address': 1}, filter_d={'address': {'$regex': '/m/'}, 'expire_time': {'$lte': int(time.time())}}): ''' read :param res_dic_k: :param fields_d: :param filter_d: :return:debug info ''' res = select_to_dic(res_dic_k, collection_name, fields=fields_d, filter=filter_d) print(res) for i in res: print(i) print(res[i]) chk() ''' 删除1个 pymongo 模糊搜索,不使用正则 python调用pymongo模糊正则查询的方法 - CSDN博客 https://blog.csdn.net/linuxpassion/article/details/52207630 # result = collection.delete_one({'address': {'$regex': '/m/'}}) # print(result) # print(result.deleted_count) # # result = collection.delete_one({'address': {'$regex': '/m/'}, 'expire_time': {'$lte': int(time.time())}}) # print(result) ''' ''' 批量删除 ''' is_to_run = True # is_to_run = False if is_to_run: myclient_db = gen_mongo_client_db() collection = myclient_db[collection_name] timestamp_ = int(time.time()) + 180 # 预估执行180秒,提前删除 filter_d = {'address': {'$regex': '/m/'}, 'expire_time': {'$lte': timestamp_}} result = collection.delete_many(filter_d) logging.info(filter_d) logging.info(result) logging.info(result.deleted_count) chk() print('------------------------') for rp in range(2): myclient_db = gen_mongo_client_db() collection = myclient_db[collection_name] # 计数 # 要统计查询结果有多少条数据,可以调用count()方法,如统计所有数据条数: filter_d = {'address': {'$regex': '/m/'}} res = collection.find(filter_d) # len=len(res) 0# object of type 'Cursor' has no len() count = res.count() print(count) logging.info(res) c_ = 0 for i in res: print(i) condition_d, udp_val_d = {'_id': i['_id']}, { '$set': {'address': i['address'].replace('/m/', '/')}} try: collection.update_one(condition_d, udp_val_d) logging.info(condition_d) logging.info(udp_val_d) c_ += 1 except Exception as e: print(e) logging.exception(e) s = '{}/{}'.format(c_, count) print(s) logging.info(s) print('chk') myclient_db = gen_mongo_client_db() collection = myclient_db[collection_name] res = collection.find_raw_batches({'address': {'$regex': '/m/'}}) for i in res: print(i)

 

    原文作者:noSql
    原文地址: https://www.cnblogs.com/yuanjiangw/p/6775842.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞