0

I have following collection

{
    "_id" : ObjectId("5b1fd21cc1448a422a21b3cc"),
    "amount" : 500,
    "bank" : "ICICI",
    "status" : "draft",
    "currency" : "EURO",
    "senderId" : ObjectId("5a16ca832bedaa6c4cb4ad97"),
    "created_date" : ISODate("2018-06-12T00:00:00.000Z")
}

I am searching for multiple criteria in it such like

const array = [
    { "status": { "$regex": searchString }},
    { "amount":  { "$regex": parseInt(searchString) }},
    { "created_date": searchString },
    { "currency": { "$regex": searchString }},
  ]

Invoice.aggregate([
    { "$match": { "$and":[{ "$or": array }] }}
])

But In above case $regex on amount searching in not working... It throws me an error...

How can I do this? I need to do this in aggregate query because I have to run $lookup for senderId

Piyush Jain
  • 185
  • 1
  • 12
  • Numbers are not strings. You cannot do a `$regex` on anything which is not a string. – Neil Lunn Jun 13 '18 at 10:15
  • @NeilLunn ok It cannot be possible for integer... So Is there any other way to do so? – Piyush Jain Jun 13 '18 at 10:17
  • Not in an aggregation `$match` no. You look like you're approaching this wrong anyway as you simply do not want to search "every" field in the document. if you're entering "text" as a search then just search the fields which have "text". If you want to let someone search by "amount", then make that a separate field in your search function and/or form. It's just makes no sense to look for "Hello" in a field which has only numeric values. And vice versa. Take the design tip and do it better. – Neil Lunn Jun 13 '18 at 10:20
  • ok thank you @NeilLunn... can I change my amount from integer to string using `$toString` or any other aggregation operator? – Piyush Jain Jun 13 '18 at 10:28
  • 3
    Don't even go there. Please listen to the plain common sense you've just been given. Forcing calculations is not what you need here. There just simply is not any valid reason to look for a string where something contains numbers. In the context of the linked duplicate, some people have "semi-valid" reasons such as searching telephone numbers. All you want is to "search every field in the document", and frankly that's just not a very smart implementation. And you can't use operators from unreleased versions anyway. Even if you did, it would need a "view" and be really slow. – Neil Lunn Jun 13 '18 at 10:37
  • Thank you @NeilLunn... You are piece of perfection I will follow your comments. thank you once again – Piyush Jain Jun 13 '18 at 10:45

0 Answers0