__author__
=
'hdfs'
import
pymongo
from
pymongo
import
MongoClient
client
=
MongoClient()
client
=
MongoClient(
'10.0.0.9'
,
27017
)
client
=
MongoClient(
'mongodb://10.0.0.9:27017/'
)
db
=
client.test_database
db.collection_names(include_system_collections
=
False
)
posts
=
db.posts
posts.find_one()
posts.find_one({
"author"
:
"Mike"
})
from
bson.objectid
import
ObjectId
post_id
=
'5728aaa96795e21b91c1aaf0'
document
=
client.db.collection.find_one({
'_id'
:
ObjectId(post_id)})
import
datetime
new_posts
=
[{
"author"
:
"Mike"
,
"text"
:
"Another
post!"
,
"tags"
:
[
"bulk"
,
"insert"
],
"date"
:
datetime.datetime(
2009
,
11
,
12
,
11
,
14
)},
{
"author"
:
"Eliot"
,
"title"
:
"MongoDB
is fun"
,
"text"
:
"and
pretty easy too!"
,
"date"
:
datetime.datetime(
2009
,
11
,
10
,
10
,
45
)}]
result
=
posts.insert_many(new_posts)
result.inserted_ids
for
post
in
posts.find():
post
for
post
in
posts.find({
"author"
:
"Mike"
}):
post
posts.count()
d
=
datetime.datetime(
2009
,
11
,
12
,
12
)
for
post
in
posts.find({
"date"
:
{
"$lt"
:
d}}).sort(
"author"
):
print
post
result
=
db.profiles.create_index([(
'user_id'
,
pymongo.ASCENDING)],unique
=
True
)
list
(db.profiles.index_information())
user_profiles
=
[
{
'user_id'
:
211
,
'name'
:
'Luke'
},
{
'user_id'
:
212
,
'name'
:
'Ziltoid'
}]
result
=
db.profiles.insert_many(user_profiles)
from
pymongo
import
MongoClient
db
=
MongoClient(
'mongodb://10.0.0.9:27017/'
).aggregation_example
result
=
db.things.insert_many([{
"x"
:
1
,
"tags"
:
[
"dog"
,
"cat"
]},
{
"x"
:
2
,
"tags"
:
[
"cat"
]},
{
"x"
:
2
,
"tags"
:
[
"mouse"
,
"cat"
,
"dog"
]},
{
"x"
:
3
,
"tags"
:
[]}])
result.inserted_ids
from
bson.son
import
SON
pipeline
=
[
{
"$unwind"
:
"$tags"
},
{
"$group"
:
{
"_id"
:
"$tags"
,
"count"
:
{
"$sum"
:
1
}}},
{
"$sort"
:
SON([(
"count"
,
-
1
),
(
"_id"
,
-
1
)])}
]
list
(db.things.aggregate(pipeline))
db.command(
'aggregate'
,
'things'
,
pipeline
=
pipeline,
explain
=
True
)