0
{
 "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]
4

3 回答 3

2

顺便说一句,Mongodb 可以找到数组中的嵌入文档:

db.school.find({ 'teachers.id' : 3 });

您可以在mongodb 文档中了解有关点符号的更多信息。

如果目标是仅返回嵌入文档,您可以使用聚合请求:

db.school.aggregate(
  {$match: { 'teachers.id' : 3 }}, 
  {$unwind : '$teachers'}, 
  {$project: { 
    _id: 0, 
    name: '$teachers.name',
    id: '$teachers.id', 
    course: '$teachers.course' 
  }}, 
  {$match: {id:3}}
);
于 2012-11-20T12:45:28.237 回答
1
school_records = db.school.find()
for i in school_records:
    for teacher in i['teachers']:
        db.individual.insert(teacher)

那这个呢?

于 2012-11-20T12:30:27.237 回答
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})})
于 2012-11-20T12:35:10.037 回答