MongoDB Aggregateを使用して、ドキュメントと配列要素の平均を取得しますか?
このために、$groupおよびaggregate()とともに$avgを使用します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo598.insertOne(
... {
... Information:'Student',
... id:100,
... details:[
... {Name:'Chris',Marks:75},
... {Name:'Bob',Marks:55}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e947fccf5f1e70e134e2694")
}
> db.demo598.insertOne(
... {
... Information:'Student',
... id:101,
... details:[
... {Name:'Chris',Marks:75},
... {Name:'Bob',Marks:45}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e947fcdf5f1e70e134e2695")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo598.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e947fccf5f1e70e134e2694"), "Information" : "Student", "id" : 100, "details" : [
{ "Name" : "Chris", "Marks" : 75 },
{ "Name" : "Bob", "Marks" : 55 }
] }
{ "_id" : ObjectId("5e947fcdf5f1e70e134e2695"), "Information" : "Student", "id" : 101, "details" : [
{ "Name" : "Chris", "Marks" : 75 },
{ "Name" : "Bob", "Marks" : 45 }
] } 以下は、ドキュメントと配列要素から平均を取得するためのクエリです-
> db.demo598.aggregate([
...
... { "$group": {
... "_id": "Information",
... "id": { "$avg": "$id" },
... "details": { "$push": "$details" }
... }},
... { "$unwind": "$details" },
... { "$unwind": "$details" },
... { "$group": {
... "_id": { "Information": "$_id", "Name": "$details.Name" },
... "id": { "$avg": "$id" },
... "AvgValue": { "$avg": "$details.Marks" }
... }},
... { "$sort": { "_id": 1 } },
... { "$group": {
... "_id": "$_id.Information",
... "id": { "$avg": "$id" },
... "details": { "$push": {
... "Name": "$_id.Name",
... "MarksAvg": "$AvgValue"
... }}
... }}
... ]).pretty(); これにより、次の出力が生成されます-
{
"_id" : "Information",
"id" : 100.5,
"details" : [
{
"Name" : "Bob",
"MarksAvg" : 50
},
{
"Name" : "Chris",
"MarksAvg" : 75
}
]
} -
配列要素の集計で平均を取得するMongoDBクエリ?
配列要素の平均を取得するには、$avgを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo584.insertOne({"Marks":[75,50,85,60,80]});{ "acknowledged" : true, "insertedId" : ObjectId("5e91d827fd2d90c177b5bcc2") } find()メソッドを使用してコレクションからすべてのドキュメントを表示する- > db
-
MongoDBドキュメントの特定のフィールドから配列要素の数を取得しますか?
特定のフィールドから配列要素をカウントするには、MongoDBで$sizeを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo723.insertOne({"Subject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab094d43417811278f588a") } >