MongoDBの2つの日付の間のフィールドをカウントして合計する方法は?
集計$gteと$lteを$sumと一緒に使用して、2つの日付の間のフィールドをカウントして合計します。まず、ドキュメントを使用してコレクションを作成しましょう-
> db.countandsumdemo.insertOne({"Value":10,"created_at":ISODate('2019-10-11')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e6df5e889d7a51994fa")
}
> db.countandsumdemo.insertOne({"Value":50,"created_at":ISODate('2019-01-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e77f5e889d7a51994fb")
}
> db.countandsumdemo.insertOne({"Value":100,"created_at":ISODate('2019-06-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038e8af5e889d7a51994fc")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.countandsumdemo.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e038e6df5e889d7a51994fa"),
"Value" : 10,
"created_at" : ISODate("2019-10-11T00:00:00Z")
}
{
"_id" : ObjectId("5e038e77f5e889d7a51994fb"),
"Value" : 50,
"created_at" : ISODate("2019-01-31T00:00:00Z")
}
{
"_id" : ObjectId("5e038e8af5e889d7a51994fc"),
"Value" : 100,
"created_at" : ISODate("2019-07-01T00:00:00Z")
} 以下は、2つの日付の間のフィールドをカウントして合計するクエリです-
> db.countandsumdemo.aggregate(
... [{
... $match: {
... created_at: {
... $gte: new Date('2019-05-01'),
... $lte: new Date('2019-12-31')
... }
... }
... }, {
... $group: {
... _id: null,
... SUM: {
... $sum: "$Value"
... },
... COUNT: {
... $sum: 1
... }
... }
... }]
... ); これにより、次の出力が生成されます-
{ "_id" : null, "SUM" : 110, "COUNT" : 2 } -
MongoDBのNumberLong(x)とNumberLong( "x")の違いは?
NumberLong(x)は制限値を超えて値を四捨五入しますが、NumberLong( x)はそうではありません。 ここで、数値を検討し、それをNumberLong(x)とNumberLong( x)の両方に使用して、違いを確認します。 ドキュメントを使用してコレクションを作成しましょう- db.demo603.insert({longValueInString:NumberLong( 988998985857575789) }); find()メソッドを使用してコレクションからすべてのドキュメントを表示する- db.demo603.find()。pretty(); これにより
-
MongoDBでカーソルの反復をカウントする方法は?
find()カーソルとともにwhileループを使用して、カスタムロジックを使用する必要があります。ドキュメントを使用してコレクションを作成しましょう- > db.demo724.insertOne( ... { ... details: ... { ... id:101, ... otherDetails:[ ...