Mongo查询日期条件和第二个集合的连接

时间:2016-10-26 16:04:34

标签: mongodb aggregation-framework

所以我有我的“用户”和“userprofile:集合,我需要找到一种方法让所有用户满足我的标准。

第一个条件是:

  

db.userprofile.find({“country”:{$ ne:“”},“州”:{$ ne:“”}}   ).Count之间()

从我的用户情况来看,我需要让所有用户都注册这样的注册日期:

  

db.user.find({created_at:{$ gte:   ISODate(“2016-04-25T00:00:00.000Z”),$ lt:   ISODate(“2016-10-27T00:00:00.000Z”)},})。count()

userprofile集合包含字段“user_id”,它与用户集合中的“id”自动生成字段基本相同。

所以问题是如何将符合日期条件的所有用户加入到符合userprofile标准的所有用户?

我尝试使用与此类似的示例,但没有成功:

  

db.user.aggregate([{         $查询:            {               来自:“userprofile”,               localField:“_ id”,               foreignField:“userid”,               as:“user_profile”           },{           $ unwind:“$ user_profile”},{         $ match:{“user_profile”:             {                 “国”:{$ NE: “”},                 “州”:{$ ne:“”}}}}}])。count()

更新

db.user.findOne()

{
    "_id" : ObjectId("561fac55c9368676ac000001"),
    "username" : "somexxx3",
    "firstname" : "Some",
    "lastname" : "User",
    "created_at" : ISODate("2015-10-15T13:38:29.954Z"),
    "enabled" : false
}

db.userprofile.findOne()

db.userprofiles.findOne()
{
    "_id" : ObjectId("56ec222017be1b7c763898a4"),
    "user_id" : ObjectId("56a77f6c17be1b0a4393d8ea"),
    "email" : "someuser@gmail.com",
    "country" : "United Sates",
    "state" : "New York"
}

如果有人可以帮助我,我会非常感激。任何提示都是受欢迎的。 感谢。

1 个答案:

答案 0 :(得分:1)

此查询应该有效:

jQuery(window).scroll(function() {
    jQuery('.arrow').css("display", "none");
});

“$ group”阶段用于计算结果(不能使用db.col.aggregate()。count())。

输出应该看起来像

db.user.aggregate([
   {
      $lookup:{
         from:"userprofiles",
         localField:"_id",
         foreignField:"user_id",
         as:"user_profile"
      }
   },
   {
      $unwind:"$user_profile"
   },
   {
      $match:{
         "user_profile.country":{
            $ne:""
         },
         "user_profile.state":{
            $ne:""
         },
         created_at:{
            $gte: ISODate("2016-04-25T00:00:00.000Z"),
            $lt: ISODate("2016-10-27T00:00:00.000Z")
         }
      }
   },
   {
      $group:{
         _id:null,
         count:{
            $sum:1
         }
      }
   }
])

其中“count”是匹配结果的数量

相关问题