【问题标题】:Adding JSON like documents to a new collection Pymongo将类似 JSON 的文档添加到新集合 Pymongo
【发布时间】:2014-12-13 07:47:52
【问题描述】:

所以现在我正在查询 mongoDB 中的现有集合,以查找所有具有以下标签的文档:“_t”:“SkeletonJoints”。拥有这些文档后,我想将其插入到一个新集合中,该集合被创建为仅保存具有用户名的这些类型的文档(例如 username_kinectdata)。

这是我的代码:

#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()

所以我的问题是当我尝试插入时,没有插入任何内容。我真的不明白为什么这不起作用。我正在尝试遍历光标.....

感谢您的帮助!

【问题讨论】:

    标签: python json mongodb pymongo querying


    【解决方案1】:

    无需转换为 JSON:PyMongo 从 MongoDB 读取 BSON 并转换为 Python dicts,当您传递 Python dict 时,PyMongo 将其转换为 BSON 并将其发送到 MongoDB。从未涉及 JSON。

    无需调用create_collection,第一次插入时MongoDB会创建一个集合。

    您的语句for line in coll.find({'_t': 'SkeletonJoints'}) 将从当前集合中检索每个文档,其中包含字段“_t”且值为“SkeletonJoints”,所以我假设不存在此类文档?您是否在 mongo shell 中尝试过以下操作?:

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

    我希望如果您执行此查询(将“MY_COLLECTION”替换为实际集合的名称),您也不会在 Mongo shell 中获得任何文档。

    【讨论】:

    • 问题是我的“_t”标签在一个名为“Meta:”的子文档中,所以我真的找不到我要找的东西。毕竟不需要转成 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多