MongoDB从另一个数组中的数组获取属性

时间:2013-10-18 21:16:39

标签: mongodb

系列是一个文件。它里面有一系列的系列(在这种情况下它有'Revenge'和'Raines')。 每个系列都有一个带名字的演员阵列。我需要一个查询来获取这些名称。

谁知道如何从两个演员阵列中获取所有名字的列表?

我最好的方法是查询db.series.find({},{_ id:0,cast:1}),其中获取带有两个强制json数组的游标。

{ series:
[ 
{ 
  name: 'Revenge',
  user_rating: 7.9,
  duration: 44,
  genres: [ ' Drama', ' Mystery', ' Thriller' ],
  year_start: '2011',
  year_end: '',
  cast: 
   [ { name: 'Madeleine Stowe' },
     { name: 'Emily VanCamp' },
     { name: 'Gabriel Mann' },
     { name: 'Nick Wechsler' },
     { name: 'Henry Czerny' },
     { name: 'Joshua Bowman' },
     { name: 'Christa B. Allen' },
     { name: 'Ashley Madekwe' },
     { name: 'Connor Paolo' },
     { name: 'Barry Sloane' },
     { name: 'Margarita Levieva' } ],
  seasons: [ { number: '3' }, { number: '2' }, { number: '1' } ]

},
{
name: 'Raines',
user_rating: 7.4,
duration: 45,
genres: [ ' Crime', ' Drama' ],
year_start: '2007',
year_end: '',
cast: 
    [ { name: 'Jeff Goldblum' },
     { name: 'Matt Craven' },
     { name: 'Nicole Sullivan' },
     { name: 'Linda Park' },
     { name: 'Dov Davidoff' },
     { name: 'Malik Yoba' },
     { name: 'Madeleine Stowe' } ],
seasons: [ { number: '1' } ] 

}
]
}

我需要这样的输出:

I need this:
         { name: 'Madeleine Stowe' },
     { name: 'Emily VanCamp' },
     { name: 'Gabriel Mann' },
     { name: 'Nick Wechsler' },
     { name: 'Henry Czerny' },
     { name: 'Joshua Bowman' },
     { name: 'Christa B. Allen' },
     { name: 'Ashley Madekwe' },
     { name: 'Connor Paolo' },
     { name: 'Barry Sloane' },
     { name: 'Margarita Levieva' },
         { name: 'Jeff Goldblum' },
     { name: 'Matt Craven' },
     { name: 'Nicole Sullivan' },
     { name: 'Linda Park' },
     { name: 'Dov Davidoff' },
     { name: 'Malik Yoba' },
     { name: 'Madeleine Stowe' }

1 个答案:

答案 0 :(得分:0)

您可以使用聚合框架:

db.series.aggregate( { $unwind : "$series" },
                     { $unwind : "$series.cast" },
                     { $group  : { _id  : "$_id",
                                   cast : {$push:"$series.cast}
                                 }
                     }
);

如果要将多个演员外观合并为一个,请将$push替换为$addToSet