2016-09-27 105 views
0

例如,我有一个收藏门类,其部分embedds文章数的嵌入式的MongoDB实例:如何使用条件(Rails)的

{ 
    "_id" : ObjectId("123123123"), 
    "articles_fields" : [ 
      { 
        "title" : "Hello world!", 
        "published_on" : ISODate("2016-09-24"), 
        "_id" : ObjectId("123123123") 
      } 
      { 
        "title" : "Hello hello!", 
        "published_on" : ISODate("2016-09-24"), 
        "_id" : ObjectId("123123123") 
      } 
    ], 
    "name" : "Common", 
    "slug" : "common" 
} 
{ 
    "_id" : ObjectId("12312312"), 
    "articles_fields" : [ 
      { 
        "title" : "Another article", 
        "published_on" : null, 
        "_id" : ObjectId("57e7b145d042ac3404e27ed0") 
      } 
    ], 
    "slug" : "software", 
    "name" : "Software" 
} 

我怎么能拿发表的文章有多少涉及到一类(有“ published_on“不等于NULL且不等于”“(空字段))。我正在考虑这一点。

我想应该是这样的:

category["articles_fields"].count(where(:published_on.ne => ["", null])) 

PS。我知道我可以使用category.articles.published.count,但我希望仅使用具有嵌入式文章的Categories集合。 谢谢!

回答

0

它将获得所有具有publish_on的文章,并将返回每个类别的计数。

db.getCollection('collection').aggregate([ 
    {$unwind:'$articles_fields'}, 
    {$match:{"articles_fields.published_on":{$ne:null}}}, 
    {$group:{_id:"$_id",document:{$push: "$$ROOT"},count:{$sum:1}}} 

    ]) 

输出:

{ 
    "_id" : ObjectId("57ea94886be4d87da7824d37"), 
    "document" : [ 
     { 
      "_id" : ObjectId("57ea94886be4d87da7824d37"), 
      "articles_fields" : { 
       "title" : "Hello world!", 
       "published_on" : ISODate("2016-09-24T00:00:00.000Z"), 
       "_id" : "123123123" 
      }, 
      "name" : "Common", 
      "slug" : "common" 
     }, 
     { 
      "_id" : ObjectId("57ea94886be4d87da7824d37"), 
      "articles_fields" : { 
       "title" : "Hello hello!", 
       "published_on" : ISODate("2016-09-24T00:00:00.000Z"), 
       "_id" : "123123123" 
      }, 
      "name" : "Common", 
      "slug" : "common" 
     } 
    ], 
    "count" : 2.0 
} 

P.S:这是正常的MongoDB的查询,因为我不是太了解Rails的语法。