-2

Collection such as:

{"_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"}

now,I want get this result:

{"_id":Obj,"fir":1,"sec":1,"trd":"xxx"}
{"_id":Obj,"fir":1,"sec":2,"trd":"few"}
{"_id":Obj,"fir":1,"sec":3,"trd":"ver"}

This means I just want to get one "sec" document for each sec.Can anyone know how to query it?

4

2 回答 2

0

我想你需要一个小组

在 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} }"
    ))

砰砰砰。由“sec”键控,但您可以更改它。

于 2012-09-14T05:29:40.193 回答
0

请注意循环顺序..意味着不能在循环下开始行

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'])
于 2014-09-25T12:07:25.603 回答