{
"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]
答案 0 :(得分:2)
顺便说一句,Mongodb可以找到数组中的嵌入式文档:
db.school.find({ 'teachers.id' : 3 });
您可以在mongodb documentation了解有关点符号的更多信息。
如果目标是仅返回嵌入文档,则可以使用aggregate请求:
db.school.aggregate(
{$match: { 'teachers.id' : 3 }},
{$unwind : '$teachers'},
{$project: {
_id: 0,
name: '$teachers.name',
id: '$teachers.id',
course: '$teachers.course'
}},
{$match: {id:3}}
);
答案 1 :(得分:1)
school_records = db.school.find()
for i in school_records:
for teacher in i['teachers']:
db.individual.insert(teacher)
这个怎么样?
答案 2 :(得分:1)
您可以使用mongo v2.2 +中的聚合命令(它位于pymongo中):
fagg=db.school.aggregate([{$unwind: "$teachers"},
{$project: {name: "$teachers.name",
id: "$teachers.id", course: "$teachers.course"}}])
fagg.result.forEach(function(o){
db.teachers.insert({_id: o.id, name: o.name, course: o.course})})