MongoDBの埋め込み配列から特定の要素を取得しますか?
特定の要素を取得するには、ドット表記で$matchを使用します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo641.insert(
... {
... ProductId:101,
... "ProductInformation":
... ( [
... {
... ProductName:"Product-1",
... "ProductPrice":1000
... },
... {
... ProductName:"Product-2",
... "ProductPrice":500
... },
... {
... ProductName:"Product-3",
... "ProductPrice":2000
... },
... {
... ProductName:"Product-4",
... "ProductPrice":3000
... }
... ]
... }
... );
WriteResult({ "nInserted" : 1 }) find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo641.find();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
[
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
} 以下は、MongoDBの埋め込み配列から特定の要素を取得するためのクエリです
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty(); これにより、次の出力が生成されます-
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
} -
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") } >