2014-10-17 52 views
0

所以現在我正在查詢mongoDB中的一個現有集合,其中包含所有標籤:「_t」:「SkeletonJoints」。獲得這些文檔後,我想將其插入到創建的新集合中,該集合僅使用用戶名(例如username_kinectdata)保存這些類型的文檔。將JSON文檔添加到新集合中Pymongo

因此,這裏是我的代碼:

#Import modules needed 
import os, pymongo, json 
from datetime import datetime 

conn = None 
db = None 
isConnected = False 

#try connecting with mongodb server 
try: 
    conn = pymongo.MongoClient() 
    db = conn.emmersiv    #connect to the emmersiv db 
    print db.collection_names()  #print the collection of files within emmersiv db 
    print "Connected to the MongoDB server" 
    isConnected = True 
except: 
    print "Connection Failed..." 

#get all collections in a list and then remove non user data 
allUsers = db.collection_names() 


'''Filtering Kinect Data By Username''' 
for users in allUsers: 
    coll = pymongo.collection.Collection(db, users.lower()) 
    print "Currently looking at", users.lower(), " to filter kinect data" 

    #find all skeletal data 
    #kinectData = coll.find({"_t": "SkeletonJoints"}) 

    newColl = users.lower() + "_kinectData" #name of the new collection to be made 

    #try to create and insert all kinect data into a new collection 
    try: 
     for line in coll.find({'_t': 'SkeletonJoints'}): 
      print line 
      jsonObj = json.loads(line)   #convert to JSON? 

      if jsonObj is not None: 
       #create collection 
       db.create_collection(newColl) 

       #and insert JSON documents 
       coll.insert(jsonObj) 

       print "Insertion finished for ", newColl 

     print "No Insertion for ", newColl 

    except pymongo.errors.CollectionInvalid: 
     print 'Collection ', newColl, ' already exists' 
    except pymongo.errors.OperationFailure: 
     print "----> OP insertion failed" 
    except pymongo.errors.InvalidName: 
     print "----> Invalid insertion Name" 
    except: 
     print "----> WTF? ", traceback.print_exc() 

所以我的問題是,當我嘗試插入,沒有什麼被插入。我不明白爲什麼這不起作用。我正在嘗試遍歷遊標.....

謝謝你的幫助!

回答

1

不需要轉換爲JSON:PyMongo從MongoDB中讀取BSON並轉換爲Python字典,並且當您將它傳遞給Python字典時,PyMongo會將其轉換爲BSON並將其發送到MongoDB。 JSON從不涉及。

不需要調用create_collection,MongoDB首次插入時會創建一個集合。

您的陳述for line in coll.find({'_t': 'SkeletonJoints'})將從當前集合中檢索具有值爲「SkeletonJoints」的字段「_t」的每個文檔,因此我推測不存在這樣的文檔?您是否嘗試過在蒙戈外殼?:

> use emmersiv 
> db.MY_COLLECTION.find({_t: "SkeletonJoints"}) 

我預計,如果你這樣做查詢(與實際徵收的名稱替換「MY_COLLECTION」),你會得到在蒙戈外殼沒有任何文件下面,無論是。

+1

問題是我的「_t」標籤在一個名爲「Meta:」的子文檔中,所以我真的找不到我在找什麼。畢竟沒有必要轉換爲JSON。 – ajl123 2014-10-20 18:48:27

+0

樂於幫助! – 2014-10-25 02:52:03