作者:从妖妖 | 来源:互联网 | 2023-05-19 10:22
pymongo模块链接mongo
1.链接单实例mongo
-
#
-
*
-
coding
:
utf
-
8
-
*
-
-
import datetime
-
import pymongo
-
import time
-
-
client
=
pymongo
.
MongoClient
(
"127.0.0.1"
,
27017
)
-
db
=
client
.
get_database
(
"collection"
)
-
db
.
authenticate
(
'collection'
,
'78hRdJEnJcHRb4qA'
)
-
#print
(
db
.
collection_names
(
)
)
-
redefine_collection
=
db
.
get_collection
(
'redefine-collection'
)
alluser=[]
-
demos
=
redefine_collection
.
find
(
{
'event_id'
:
'0109001'
,
'event_info.url'
:
{
'$exists'
:
'true'
}
,
"ctime"
:
{
"$gte"
:
1525881600000}}
,
no_cursor_timeout
=
True
)
-
for
item
in
demos
:
-
if
len
(
item
[
'event_info'
]
[
'url'
]
.
replace
(
r
'/'
,
''
)
.
split
(
'.'
)
[
-
1
]
)
<
=
5
:
-
alluser
.
append
(
item
[
&#39;event_info&#39;
]
[
&#39;url&#39;
]
.
replace
(
r
&#39;/&#39;
,
&#39;&#39;
)
.
split
(
&#39;.&#39;
)
[
-
1
]
)
-
demos
.
close
(
)
-
print len
(
alluser
)
-
2.连接复制集
-
from pymongo import MongoClient
-
conn
=
MongoClient
(
[
&#39;192.168.3.11:27017&#39;
,
&#39;192.168.3.12:27017&#39;
,
&#39;192.168.3.13:27017&#39;
],replicaset=&#39;shard1&#39;
)
-
from pymongo import ReadPreference
-
db
=
conn
.
get_database
(
&#39;hnrtest&#39;
,
read_preference
=
ReadPreference
.
SECONDARY_PREFERRED
)
3.mongo常见操作
# #####read client
# client = pymongo.MongoReplicaSetClient([&#39;172.31.46.25:27017,172.31.43.36:27017,172.31.40.242:27017&#39;],replicaset=&#39;shard1&#39;)
# db = client.get_database("collection")
# db.authenticate(&#39;collection&#39;, &#39;78hRdJEnJcHRb4qA&#39;)
#
# print db.client.read_preference
# print db.client.primary
# print db.client.secondaries
# print db.client.arbiters
# print db.command(&#39;ismaster&#39;)
#####read client
client = pymongo.MongoClient([&#39;172.31.32.223:20000&#39;])
db = client.get_database("admin")
db.authenticate(&#39;admin&#39;, &#39;ggxP6tPI971K3W0r&#39;)
# print db.client.read_preference
# print db.client.primary
# print db.client.secondaries
# print db.client.arbiters
# print db.client.is_primary
# print db.command(&#39;ismaster&#39;)
# print db.command(&#39;currentOp&#39;)
# print db.command(&#39;replSetGetStatus&#39;)
# print db.list_collection_names()
statement=client.collection.get_collection(&#39;statement&#39;) ###获取对应db下的对应集合
print statement.count()
# client.collection.add_user(&#39;newTestUser&#39;, &#39;Test123&#39;, roles=[{&#39;role&#39;:&#39;readWrite&#39;,&#39;db&#39;:&#39;collection&#39;}]) ####添加用户
# client.collection.remove_user(&#39;newTestUser&#39;) ####删除用户
db2 = client.get_database("collection")
db2.add_user(&#39;newTestUser&#39;, &#39;Test123&#39;, roles=[{&#39;role&#39;:&#39;readWrite&#39;,&#39;db&#39;:&#39;collection&#39;}]) ###添加用户
print db.current_op()
# options = {&#39;lock&#39;: True}
# db.client.fsync(**options)
# print db.client.is_locked
# ####
# print db.command(&#39;fsyncUnlock&#39;)
# print db.client.is_locked
-
参考:http
:
/
/
blog
.
51cto
.
com/hnr520/1874506