Mongodb:根据其他集合中的键值组合两个集合来获取数据 - (mongoid - rails4)

时间:2015-09-07 18:13:34

标签: ruby-on-rails mongodb mapreduce mongoid

我试图通过组合“bolg_post”和“User”doc来获得结果集。

blog_post # embeds many comments doc
{ 
  "_id" : ObjectId( "55ea003e4102135d9d000677" ),
  "text" : "This is a post about natural beauties of hawaii.. blah blah..",
  "author_id": "345345026743545647567567", # references to User doc id
  "updated_at" : Date( 1441398846696 ),
  "created_at" : Date( 1441398846696 ),
  "comments" : [ 
    { "_id" : ObjectId( "55ea003e4102135d9d000002" ),
      "text" : "Very good article",
      "user_id": "83753iy45735y84934759",
      "updated_at" : Date( 1441400501867 ),
      "created_at" : Date( 1441400501867 )
    }, 
    { "_id" : ObjectId( "345a003e41026743545645454" ),
      "text" : "Hawaii is my fav",
      "user_id" : "55e7668c4102132ea8000066", # references to User doc id
      "updated_at" : Date( 1441400501867 ),
      "created_at" : Date( 1441400501867 )
    } 
  ] 
}

User # has many blog_posts

{ 
  "_id" : ObjectId( "83753iy45735y84934759" ),
  "name" : "John abc",
  "status": "active", # could be inactive, pending, deleted etc.
  "age": 29,
  "updated_at" : Date( 1441400501867 ),
  "created_at" : Date( 1441400501867 )
}

{ 
  "_id" : ObjectId( "55e7668c4102132ea8000066" ),
  "name" : "Lisa xyz",
  "status": "inactive", # could be inactive, pending, deleted etc.
  "age": 24,
  "updated_at" : Date( 1441400501867 ),
  "created_at" : Date( 1441400501867 )
}

{ 
  "_id" : ObjectId( "345345026743545647567567" ),
  "name" : "David uyi",
  "status": "active", # could be inactive, pending, deleted etc.
  "age": 39,
  "updated_at" : Date( 1441400501867 ),
  "created_at" : Date( 1441400501867 )
}

我想只获取那些博客文章,其作者状态在用户文档中处于活动状态。 同样,我想只获得一篇帖子的评论,这些评论由状态在用户文档中处于活动状态的用户发布

{ 
  "blog_id" : "55ea003e4102135d9d000677",
  "text" : "This is a post about natural beauties of hawaii.. blah blah..",
  "author": {
    "author_id": "345345026743545647567567",
    "name" : "David uyi",
    "age": 39
  }
  "updated_at" : Date( 1441398846696 ),
  "created_at" : Date( 1441398846696 ),
  "comments" : [ 
    { "comment_id" : ObjectId( "55ea003e4102135d9d000002" ),
      "text" : "Very good article",
      "user" : {
        "user_id": 
        "name" : "John abc",
        "age": 29
      }
    }
    # here Lisa's comment is not shown as she is inactive
  ] 
}

但是我想要的是分页,这意味着,假设每个查询结果只需要5条记录(限制为0,5)。 因此,最简单的方法是获取前5个blog_post文档。然后从中获取user_id,然后转到User doc和 然后查找这些用户是否处于活动状态。如果没有,则删除这些条目。但是这样,我最终可能会少于 5结果集。那我怎么能一气呵成呢。假设我有100,00,00个用户和100,000个帖子。所以这将是糟糕的设计   如果我按照我之前谈到的方式行事,而不是一气呵成

0 个答案:

没有答案