2016-06-29 8 views
1

は、これは私が私が特定の年と特定の月のとでレコードだけをしたいmongodbで特定の月の日の賢明な記録を得るには?

{ "_id" : { "year" : 2015, "month" : 8, "day" : 15 }, "sum" : 200 } 
{ "_id" : { "year" : 2016, "month" : 5, "day" : 20 }, "sum" : 150 } 
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 250 } 

として出力を取得しています

db.expenses.aggregate([ 
    { 
     $project: { 
      _id: 1, 
      year: { $year: "$createdat" }, 
      month: { $month: "$createdat" }, 
      day: { $dayOfMonth: "$createdat" }, 
      expenseprice: 1 
     } 
    }, 
    { 
     $group: { 
      _id: { 
       year: "$year", 
       month: "$month", 
       day: "$day" 
      }, 
      sum: { $sum: "$expenseprice" } 
     } 
    } 
]) 

このクエリを試してみました

empname: {type: String}, 
soldby: {type: String}, 
expenseprice:{type:Number}, 
expensedesc:{type:String}, 
expensetype:{type:String}, 
createdat: {type: Date, default: Date.now} 

私のスキーマですその月、このような日の賢明

{ "_id" : { "year" : 2016, "month" : 6, "day" : 28 }, "sum" : 150 } 
{ "_id" : { "year" : 2016, "month" : 6, "day" : 29 }, "sum" : 200 } 

は、私があまりにも

db.expenses.aggregate([ 
    { 
     $project: { 
      _id: 1, 
      year: { $year: "$createdat" }, 
      month: { $month: "$createdat" }, 
      day: { $dayOfMonth: "$createdat" }, 
      expenseprice: 1 
     } 
    }, 
    { 
     $match: { 
      $eq: ["$month", 06] 
     } 
    }, 
    { 
     $group: { 
      _id: { 
       year: "$year", 
       month: "$month", 
       day: "$day" 
      }, 
      sum: { $sum: "$expenseprice" } 
     } 
    } 
]) 

$matchを試してみました。しかし、私はこの

assert: command failed: { 
    "ok" : 0, 
    "errmsg" : "bad query: BadValue unknown top level operator: $eq", 
    "code" : 16810 
} : aggregate failed 
[email protected]/mongo/shell/utils.js:23:13 
[email protected]/mongo/shell/assert.js:13:14 
[email protected]/mongo/shell/assert.js:266:5 
[email protected]/mongo/shell/collection.js:1215:5 
@(shell):1:1 

2016-06-29T16:20:47.754+0530 E QUERY [thread1] Error: command failed: { 
    "ok" : 0, 
    "errmsg" : "bad query: BadValue unknown top level operator: $eq", 
    "code" : 16810 
} : aggregate failed : 
[email protected]/mongo/shell/utils.js:23:13 
[email protected]/mongo/shell/assert.js:13:14 
[email protected]/mongo/shell/assert.js:266:5 
[email protected]/mongo/shell/collection.js:1215:5 
@(shell):1:1 

答えて

1

$グループで年と月を参照することができる方法については、以下のサンプルを参照してくださいのようなエラーになっています。私の理解によれば、それはあなたの要件に必要な最後のビットです。

db.expenses.aggregate([ 
    {$project: {_id:1,year:{$year:"$createdat"},month:{$month:"$createdat"}, day:{$dayOfMonth:"$createdat"},expenseprice:1}}, 
    {$group: {_id:{year:"$year",month:"$month",day:"$day"}, sum:{$sum:"$expenseprice"}}}, 
    {$match : {"_id.year" : 2016, "_id.month" : 6}}]) 

マッチの後に別のグループを追加した理由がわかりません。私の最初の理解から、それは必要とされないかもしれません。上記の解決策が期待通りでない場合は、コメントまたは要件を更新してください。私はそれに応じて答えを調整します。

いくつかのサンプルデータでクエリをテストしました。データは1ヶ月間フィルタリングされ、私はその日の賢明な内訳を取得します。

関連する問題