收集如:
{"_id":Obj,"fir":1,"sec":1,"trd":"xxx"}
{"_id":Obj,"fir":1,"sec":2,"trd":"few"}
{"_id":Obj,"fir":1,"sec":3,"trd":"ver"}
{"_id":Obj,"fir":1,"sec":1,"trd":"xfsd"}
{"_id":Obj,"fir":1,"sec":2,"trd":"cdsv"}
{"_id":Obj,"fir":1,"sec":3,"trd":"xedsv"}
{"_id":Obj,"fir":1,"sec":1,"trd":"crv"}
{"_id":Obj,"fir":1,"sec":2,"trd":"cre"}
{"_id":Obj,"fir":1,"sec":3,"trd":"xewfr"}
{"_id":Obj,"fir":2,"sec":1,"trd":"xxx"}
{"_id":Obj,"fir":2,"sec":2,"trd":"few"}
{"_id":Obj,"fir":2,"sec":3,"trd":"ver"}
{"_id":Obj,"fir":2,"sec":1,"trd":"xfsd"}
{"_id":Obj,"fir":2,"sec":2,"trd":"cdsv"}
{"_id":Obj,"fir":2,"sec":3,"trd":"xedsv"}
{"_id":Obj,"fir":2,"sec":1,"trd":"crv"}
{"_id":Obj,"fir":2,"sec":2,"trd":"cre"}
{"_id":Obj,"fir":2,"sec":3,"trd":"xewfr"}
现在,我想得到这个结果:
{"_id":Obj,"fir":1,"sec":1,"trd":"xxx"}
{"_id":Obj,"fir":1,"sec":2,"trd":"few"}
{"_id":Obj,"fir":1,"sec":3,"trd":"ver"}
这意味着我只想每秒获得一个“秒”文档。任何人都知道如何查询它?
答案 0 :(得分:0)
我认为你想要group。
在mongo shell中,这有效:
db.test.group({reduce: function(doc, out) {if (!out[doc.sec]) {out[doc.sec] = doc} }, initial:{}})
的产率:
[
{
"1" : {
"_id" : ObjectId("5052bd3d89e42529f53462d3"),
"fir" : 1,
"sec" : 1,
"trd" : "xxx"
},
"2" : {
"_id" : ObjectId("5052bd3d89e42529f53462d4"),
"fir" : 1,
"sec" : 2,
"trd" : "few"
},
"3" : {
"_id" : ObjectId("5052bd3d89e42529f53462d5"),
"fir" : 1,
"sec" : 3,
"trd" : "ver"
}
}
]
在pymongo中,将js函数包装在一个字符串和一个bson.Code:
中db.test.group({},{},{},bson.Code(
"function(doc, out) {if (!out[doc.sec]) {out[doc.sec] = doc} }"
))
Bing bang热潮。用“秒”键入,但你可以改变它。
答案 1 :(得分:0)
请注意循环序列。不能在循环
下启动.means行from pymongo import MongoClient
connection = MongoClient('mongodb://localhost:27017/')
db = connection.students.ctec121
student_record = {}
print()
# set flag variable
flag = True
print()
# loop for data input
while (flag):
# ask for input
student_name = input("Enter student name")
student_grade=input("enter grade student")
# place values in dictionary
student_record = {'name':student_name,'grade':student_grade}
# insert the record
db.insert(student_record)
# should we continue?
flag = input('Enter another record? ')
if (flag[0].upper() == 'N'):
flag = False
# find all documents
results = db.find()
for record in results:
print(record['name'] + ',',record['grade'])