0

I need to perform $lookup aggregate and merge objects based on regex match. One collection is having regex match pattern. So based on these patterns, need to perform search on another collection.

I have two collections. (1) messages and (2) regexes. Here is output of message collection.


[{_id: ObjectId(...), message: I had a dinner at McDonald}, 
{_id: ObjectId(...), message: I booked my ticket from TicketWorld},
{_id: ObjectId(...), message: I spent my weekend at Paris},
{_id: ObjectId(...), message: I went to Paris},
{_id: ObjectId(...), message: I like McDonald}]
Here is output of regexes collection.

[{_id: ObjectId(...), regexMatch: /mcdonald/gi, ratePoint:3}, 
{_id: ObjectId(...), regexMatch: /paris/gi, ratePoint:4},
{_id: ObjectId(...), regexMatch: /ticketwor/gi, ratePoint:2]

I tried with following code. But could not perform regex search and hence not able to merge the objects.


db.messages.aggregate([ 
{
$lookup: {
from: "regexes",
localField: "message",
foreignField: "regexMatch",
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
])

Expected output is as follows:


[{_id: ObjectId(...), message: I had a dinner at McDonald, ratePoint: 3}, 
{_id: ObjectId(...), message: I booked my ticket from TicketWorld ,ratePoint: 2},
{_id: ObjectId(...), message: I spent my weekend at Paris, ratePoint: 4},
{_id: ObjectId(...), message: I went to Paris, ratePoint: 4},
{_id: ObjectId(...), message: I like McDonald, ratePoint: 3}]

Malik Awan
  • 463
  • 5
  • 13

0 Answers0