Importing data into a local MONGO
Mongoimport--db test--collection restaurants--drop--file Primer-dataset.json
If the test database is already in the local MONGO database, the above command deletes the previous data and then imports the new data
Install Pymongo in Linux/os X
Pip Install Pymongo
Insert data:
# test.py
From Pymongo import mongoclient
Client = Mongoclient () # If not specified, the default connection is 27017 ports local
db = client.test # DB represents the MONGO test database
Table = Db.person # If there is no person in the test, MongoDB creates a person
#mongo中存储的数据类似json对象
From datetime import datetime
data = {
"Name": "Jack",
"Sex": "Male",
"Age": 20,
"Birth": Datetime.strptime ("1995-12-23", "%y-%m-%d"),
"Hobby": ["Football", "basketball"],
"Grades": {
"Grade": "A"
"Score": 80
}
"Detail": [
{"Father": "xxxx", "Mather": "FFFFFF"}
{"Father": "Country", "Mather": "God"}
]
}
P1 = Table.insert_one (data)
#mongodb will automatically add a _id domain by default
Print people.inserted_id
# Insert multiple data can use Insert_many,insert_many with default parametersOrdered=true
P2 = Table.insert_many ({"Name": i} for I in range (3))
Print P2.inserted_ids
Query data:
person = Table.find () #查找person表的所有信息
Person = Table.find ({' Age ': $}) #查询年龄是20的person
Person = Table.find ({"Age": $, "detail.father": "Country"}) #查询年龄是20并且father是country的person
Person = Table.find ({"Grades.score": {"$GT":}}) #查询分数大于70的person
Person = Table.find ({"$or": [{"Sex": "Female"}, {"Grades.grade": "A"}]}) #查询性别为女或者成绩为A
person = Table.find (). Sort ([(' Age ', Pymongo. Ascending), ("Grades.score", Pymongo. Descending)]) #查询person表所有记录并先按照年龄升序, and then descending by fractions
select = {"Birth": {"$lt": DateTime.Now ()}}
Group = {"_id": "$grades. Grade", "Count": {"$sum": 1}}
Match = Dict (SELECT, **{"Hobby": "Football"})
Pipeline = [
{"$match": Match}, # Matching Criteria
{"$unwind": "$grades"} #要以grades中的grade为分组条件要首先把grades查询解析出来
{"$group": group}, #分组条件
{"$limit": 10} # Limit the number of query bars to 10
]
Person = table.aggregate (pipeline)
When the name of the table is not fixed as a variable, get table through
Table = db["person_%s"% variable] this way
Analysis of MongoDB (based on Python,linux)