Convert string to double and compare with in array of objects

Here is my mongo sample collection,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"_id" : ObjectId("62aeb8301ed12a14a8873df1"),
"Fields" : [
{
"FieldId" : "name",
"Value" : [ "test_123" ]
},
{
"FieldId" : "mobile",
"Value" : [ "123" ]
},
{
"FieldId" : "amount",
"Value" : [ "300" ]
},
{
"FieldId" : "discount",
"Value" : null
}
]
}
</code>
<code>{ "_id" : ObjectId("62aeb8301ed12a14a8873df1"), "Fields" : [ { "FieldId" : "name", "Value" : [ "test_123" ] }, { "FieldId" : "mobile", "Value" : [ "123" ] }, { "FieldId" : "amount", "Value" : [ "300" ] }, { "FieldId" : "discount", "Value" : null } ] } </code>
{
   "_id" : ObjectId("62aeb8301ed12a14a8873df1"),
   "Fields" : [ 
    {
        "FieldId" : "name",
        "Value" : [ "test_123" ]
    }, 
    {
        "FieldId" : "mobile",
        "Value" : [ "123" ]
    }, 
    {
        "FieldId" : "amount",
        "Value" : [ "300" ]
    }, 
    {
        "FieldId" : "discount",
        "Value" : null
    }
  ]
 }

Here I want to get the matched record like “Fields.FieldId” should be equal to “amount” and “Fields.Value.0” should be greater than 0 or something else given.

Please note down below points,

  • Fields.Value” might null too
  • Sometime some of the fields may not appear in the array also

I have tried like below which is not working,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>db.form.aggregate([
{
$match:
{
{
$expr: {
$ne: [
{ $filter: {
input: '$Fields',
cond: { if: {$eq:["$$this.FieldId", "amount"]},
then:{$gte: [{$toDouble: "$$this.Value.0"}, 0]} }
}
}, []
]
}
}
}
}])
</code>
<code>db.form.aggregate([ { $match: { { $expr: { $ne: [ { $filter: { input: '$Fields', cond: { if: {$eq:["$$this.FieldId", "amount"]}, then:{$gte: [{$toDouble: "$$this.Value.0"}, 0]} } } }, [] ] } } } }]) </code>
db.form.aggregate([
{
  $match:
  {
    {
       $expr: {
          $ne: [
             { $filter: { 
                input: '$Fields', 
                  cond: { if: {$eq:["$$this.FieldId", "amount"]}, 
                          then:{$gte: [{$toDouble: "$$this.Value.0"}, 0]} }
                  } 
               }, []
           ]
         }
      }
    }
}])

I don’t want to use $project or $addFields. I just want to do direct $match query. Please suggest me if it is possible.

Thanks in advance,
Mani

One of the canonical ways to perform element-wise checking on an array field would be using $anyElementTrue. You can first use $map to apply your condition(s) on the array to project a boolean array and apply $anyElementTrue on it.

  1. use $map to iterate through the Fields array
  2. check if the FieldId is equal to amount
  3. try to $convert the string value into double.
    • if convert succeed, we keep the double value
    • if convert failed, says it is non-number, we fallback to default value of 0.0(or any value that is less than zero). So this query won’t throw an exception even if your data does not have a value that is parseable into double.
  4. chain up the condition of 2 and 3 in an $and and compare with 0. If the conversion failed, it will fall back to 0.0 and will not be selected.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>db.collection.aggregate([
{
"$match": {
$expr: {
"$anyElementTrue": {
"$map": {
"input": "$Fields",
"as": "f",
"in": {
"$and": [
{
"$eq": [
"amount",
"$$f.FieldId"
]
},
{
$gt: [
{
"$convert": {
"input": {
"$first": "$$f.Value"
},
"to": "double",
"onError": 0.0,
"onNull": 0.0
}
},
0
]
}
]
}
}
}
}
}
}
])
</code>
<code>db.collection.aggregate([ { "$match": { $expr: { "$anyElementTrue": { "$map": { "input": "$Fields", "as": "f", "in": { "$and": [ { "$eq": [ "amount", "$$f.FieldId" ] }, { $gt: [ { "$convert": { "input": { "$first": "$$f.Value" }, "to": "double", "onError": 0.0, "onNull": 0.0 } }, 0 ] } ] } } } } } } ]) </code>
db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$anyElementTrue": {
          "$map": {
            "input": "$Fields",
            "as": "f",
            "in": {
              "$and": [
                {
                  "$eq": [
                    "amount",
                    "$$f.FieldId"
                  ]
                },
                {
                  $gt: [
                    {
                      "$convert": {
                        "input": {
                          "$first": "$$f.Value"
                        },
                        "to": "double",
                        "onError": 0.0,
                        "onNull": 0.0
                      }
                    },
                    0
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
])

Mongo Playground

1

  1. Use the $and operator to match multiple conditions instead of if and then.

  2. Use the $first operator to get the first element from the array.

  3. Also, you have additional braces {} in the $match stage that break the query. Remove the additional braces {}.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
{
$filter: {
input: "$Fields",
cond: {
$and: [
{
$eq: [
"$$this.FieldId",
"amount"
]
},
{
$gte: [
{
$toDouble: {
$first: "$$this.Value"
}
},
0
]
}
]
}
}
},
[]
]
}
}
}
])
</code>
<code>db.collection.aggregate([ { $match: { $expr: { $ne: [ { $filter: { input: "$Fields", cond: { $and: [ { $eq: [ "$$this.FieldId", "amount" ] }, { $gte: [ { $toDouble: { $first: "$$this.Value" } }, 0 ] } ] } } }, [] ] } } } ]) </code>
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          {
            $filter: {
              input: "$Fields",
              cond: {
                $and: [
                  {
                    $eq: [
                      "$$this.FieldId",
                      "amount"
                    ]
                  },
                  {
                    $gte: [
                      {
                        $toDouble: {
                          $first: "$$this.Value"
                        }
                      },
                      0
                    ]
                  }
                ]
              }
            }
          },
          []
        ]
      }
    }
  }
])

Demo @ Mongo Playground

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật