1

私はNodeJs + MongoDB(Mongoose)の学習を始めました。 クエリに問題があります。今月の誕生日を持つすべてのユーザーを選択してください

私はが必要です今月の誕生日を持つすべてのユーザーを選択してください


ユーザーのスキーマ:コレクションの

const UserSchema = new mongoose.Schema({ 
    email: { 
     type: String, 
     unique: true, 
     required: true, 
     index: true 
    }, 
    password: { 
     type: String, 
     required: true 
    }, 
    firstName: { 
     type: String, 
     required: true 
    }, 
    lastName: { 
     type: String, 
     required: true 
    }, 
    phone: { 
     type: String, 
     required: true 
    }, 
    birthday: { 
     type: Date, 
     required: true 
    }, 
    photo: { 
     type: String, 
     required: false 
    }, 
    updated: { 
     type: Date, 
     default: Date.now 
    } 
}); 

例(ユーザー)文書:

{ 
    "__v" : NumberInt(0), 
    "_id" : ObjectId("589b26ab4490e29ab5bdc17c"), 
    "birthday" : ISODate("1982-08-17T00:00:00.000+0000"), 
    "email" : "[email protected]", 
    "firstName" : "John", 
    "lastName" : "Smith", 
    "password" : "$2a$10$/NvuIGgAYbFIFMMFW1RbBuRGvIFa2bOUQGMrCPRWV7BJtrU71PF6W", 
    "phone" : "1234567890", 
    "photo" : "photo-1486565456205.jpg", 
    "updated" : ISODate("2017-02-08T14:09:47.215+0000") 
} 
+0

重複。この質問をチェックアウト:[回答1](http://stackoverflow.com/questions/34614042/how-to-get-list-of-users-whos-birthday-is-today-in-mongodb) – ZombieChowder

答えて

2

現在の月に誕生日を持つすべてのユーザーの一覧を取得するには、改訂を行うには$condオペレータの助けを借りて、文書をフィルタリングする$redactパイプラインを使用して集約演算を実行する必要があります。次のパイプラインを実行する検討:

User.aggregate([ 
    { 
     "$redact": { 
      "$cond": [ 
       { 
        "$eq": [ 
         { "$month": "$birthday" }, 
         { "$month": new Date() } 
        ] 
       } 
      ], 
      "$$KEEP", 
      "$$PRUNE" 
     } 
    } 
]).exec(function(err, docs){ 
    if (err) throw err; 
    console.log(docs); 
}); 

"$cond": [ 
    { 
     "$eq": [ 
      { "$month": "$birthday" }, 
      { "$month": new Date() } 
     ] 
    } 
], 

上記$cond発現は、本質的に

if (birthday.getMonth() === (new Date()).getMonth()) { 
    "$$KEEP" // keep the document in the pipeline 
} else { 
    "$$PRUNE" // prune/discard the document from the output 
} 

条件文を表しますパイプラインは、すべての文書が$monthdate operatorに基づいて$condによって返さ$$KEEPシステム変数との条件に合致し、$$PRUNEとそれ以外の文書を破棄返されます。

0

あなたが入力日付を持っている場合は、fromDateからtoDateまで、つまり、単純なクエリ:

db.collection.find({"birthday":{$gte: fromDate, $lte: toDate}}); 
+0

これは決して動作しませんあなたが1年間だけフィルタリングしているからです。 –

関連する問題