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
}
}
]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP