特定のMongoDBドキュメント内のオブジェクトの配列から特定のオブジェクトを取得するにはどうすればよいですか?
オブジェクトの配列から特定のオブジェクトを取得するには、定位置演算子($)を使用します。まず、ドキュメントを使用してコレクションを作成しましょう-
> db.getASpecificObjectDemo.insertOne(
... {
... _id :1,f
... "CustomerName" : "Larry",
... "CustomerDetails" : {
... "CustomerPurchaseDescription": [{
... id :100,
... "ProductName" : "Product-1",
... "Amount":10000
... },{
... id :101,
... "ProductName" : "Product-2",
... "Amount":10500
... },
... {
... id :102,
... "ProductName" : "Product-3",
... "Amount":10200
... }
... ]
... }
... }
... );
{ "acknowledged" : true, "insertedId" : 1 } 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.getASpecificObjectDemo.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : 1,
"CustomerName" : "Larry",
"CustomerDetails" : {
"CustomerPurchaseDescription" : [
{
"id" : 100,
"ProductName" : "Product-1",
"Amount" : 10000
},
{
"id" : 101,
"ProductName" : "Product-2",
"Amount" : 10500
},
{
"id" : 102,
"ProductName" : "Product-3",
"Amount" : 10200
}
]
}
} 以下は、特定のMongoDBドキュメント内のオブジェクトの配列から特定のオブジェクトを取得するためのクエリです-
> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1}); これにより、次の出力が生成されます-
{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } } -
MongoDB Aggregateを使用して、ドキュメントと配列要素の平均を取得しますか?
このために、$groupおよびaggregate()とともに$avgを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo598.insertOne( ... { ... Information:'Student', ... id:100, ... details:[ ... {Name:'Chris',Ma
-
MongoDBドキュメントの特定のフィールドから配列要素の数を取得しますか?
特定のフィールドから配列要素をカウントするには、MongoDBで$sizeを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo723.insertOne({"Subject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab094d43417811278f588a") } >