MongoDB查询以使用多个条件(范围)在数组中查找值

要在某个范围内的数组中查找值,请使用$gt和$lt。让我们创建一个包含文档的集合-

> db.demo341.insertOne({

...    "Name": "Chris",

...       "productDetails" : [

...          {

...             "ProductPrice" : {

...             "Price" : 800

...          }

...       },

...       {

...          "ProductPrice" : {

...             "Price" : 400

...          }

...       },

...       {

...       "ProductPrice" : {

...          "Price" : 300

...          }

...       }

...    ]

... }

... );

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5e53ed5cf8647eb59e5620a7")

}

> db.demo341.insertOne({

...    "Name": "Chris",

...       "productDetails" : [

...          {      

...             "ProductPrice" : {

...                "Price" : 1000

...             }

...          },

...          {

...          "ProductPrice" : {

...             "Price" : 1200

...          }

...       },

...       {

...          "ProductPrice" : {

...             "Price" : 1300

...          }

...       }

...    ]

... }

... );

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5e53edc1f8647eb59e5620a8")

}

find()方法的帮助下显示集合中的所有文档-

> db.demo341.find();

这将产生以下输出-

{

   "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [

      { "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } },

      { "ProductPrice" : { "Price" : 300 } }

   ]

}

{

   "_id" : ObjectId("5e53edc1f8647eb59e5620a8"), "Name" : "Chris", "productDetails" : [

      { "ProductPrice" : { "Price" : 1000 } }, { "ProductPrice" : { "Price" : 1200 } },

      { "ProductPrice" : { "Price" : 1300 } }

   ] 

}

以下是在具有多个条件的数组中查找值的查询-

> db.demo341.aggregate([

...    { "$match": {

...       "productDetails": {

...          "$elemMatch": {

...          "ProductPrice.Price": {

...             "$gt": 600,

...             "$lt": 900

...          }

...       }

...    }

... }}

... ]).pretty();

这将产生以下输出-

{

   "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"),

   "Name" : "Chris",

   "productDetails" : [

      {

         "ProductPrice" : {

            "Price" : 800

         }

      },

      {

         "ProductPrice" : {

            "Price" : 400

         }

      },

      {

         "ProductPrice" : {

            "Price" : 300

         }

      }

   ]

}

以上是 MongoDB查询以使用多个条件(范围)在数组中查找值 的全部内容, 来源链接: utcz.com/z/354292.html

回到顶部