MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

Mongoを使用して、フィルタリングされたサブドキュメントを含むドキュメントを返すにはどうすればよいですか?


これには、MongoDBで$projectを使用します。その中で、$filterを使用します。ドキュメントを使用してコレクションを作成しましょう-

> db.demo457.insertOne(
... {
...    _id: 101,
...    details: [
...       { ProductName:"Product-1" , ProductPrice:90 },
...       { ProductName:"Product-2" , ProductPrice:190 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo457.insertOne(
... {
...    _id: 102,
...    details: [
...       { ProductName:"Product-3" , ProductPrice:150},
...       { ProductName:"Product-4" , ProductPrice:360 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }

find()メソッドを使用してコレクションからすべてのドキュメントを表示する-

> db.demo457.find();

これにより、次の出力が生成されます-

{ "_id" : 101, "details" : [ { "ProductName" : "Product-1", "ProductPrice" : 90 }, { "ProductName"
: "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-3", "ProductPrice" : 150 }, {
"ProductName" : "Product-4", "ProductPrice" : 360 } ] }

以下は、MongoDBを使用してフィルタリングされたサブドキュメントを含むドキュメントを返すクエリです-

> db.demo457.aggregate([
... {
...    $project: {
...       details: {
...          $filter: {
...             input: "$details",
...             as: "output",
...             cond: { $gte: [ "$$output.ProductPrice", 170 ] }
...          }
...       }
...    }
... }
... ])

これにより、次の出力が生成されます-

{ "_id" : 101, "details" : [ { "ProductName" : "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-4", "ProductPrice" : 360 } ] }

  1. JavaScriptを使用してCookieを読み取る方法は?

    以下は、JavaScriptを使用してCookieを読み取るためのコードです- 注 −この例を実行するには、ローカルサーバーが必要です。 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Documen

  2. mongosコマンドを使用してMongoDBシェルを実行するにはどうすればよいですか?

    MongoDBシェルを起動するには、mongoコマンドを使用する必要があります。以下は構文です- >mongo 以下のスクリーンショットのように、最初にコマンドプロンプトからMongoDBbinディレクトリにアクセスします- 以下のスクリーンショットのように、mongoシェルを起動するコマンドは次のとおりです- これにより、次の出力が生成されます-