{
"teachers" : [
{"name": "Lucy", "id": 3, course: "history"},
{"name": "Mark", "id": 6, "course": "maths"},
{"name": "Joan", "id": 20, course: "French"}
]
}
该文件在“学校”收藏中。我一直在尝试使用
db.school.find({teachers:{id:3}})
我也试过
db.school.find({teacher.id:3})
但我知道它不起作用,因为 mongo 无法查看嵌入式数组。因此,我想将这些嵌入的文档变成单独的文档。也就是说,删除嵌入和“教师”键,为每个教师创建一个单独的文档。
最终的“学校”系列将是
{"name": "Lucy", "id": 3, "course": "history"},
{"name": "Mark", "id": 6, "course": "maths"},
{"name": "Joan", "id": 20, "course": "French"}
我想用 python 来做,并将新文档保存到一个集合中。
编辑
这就是我现在想出的:
import pymongo
import sys
connection = pymongo.Connection("mongodb://localhost", safe=True)
db = connection.hello
shows = db.school
for doc in db.school:
for indiv in "teachers":
try:
db.individual.insert(indiv)
except:
print "Unexpected error", sys.exc_info()[0]