如何从mongodb获取记录?

时间:2014-02-17 14:38:07

标签: mongodb

我有像

这样的mongodb集合
{
   id : 'd8fsd7f8sdfsd8f8ds7fsd8',
   books : [
          {"author" : "['b1']" , "date" : 2-3-00, name: 'a'},
          {"author" : "['b1', 'b2']" , "date" : 4-10-00, name: 'b'},
          {"author" : "['b2']" , "date" : 5-3-00, name: 'c'},
          {"author" : "['b2']" , "date" : 6-12-00, name: 'd'}, ]
 }

如何通过mongo查询获取包含作者“b2”的数据,如

{
   id : 'd8fsd7f8sdfsd8f8ds7fsd8',
   books : [
         {"author" : "['b1', 'b2']" , "date" : 4-10-00, name: 'b'},
          {"author" : "['b2']" , "date" : 5-3-00, name: 'c'},
          {"author" : "['b2']" , "date" : 6-12-00, name: 'd'}, ]
 }

1 个答案:

答案 0 :(得分:1)

我假设您的收藏名称为books。你可以做那个aggregation框架

db.books.aggregate(
    { $unwind: '$books'},
    { $match: {'books.book1': {$eq: "b2"}}},
    { $group: {books: {$push: '$books.book1'}}})