0

I want to write a mongodb query that allows me to fetch array objects fields based on the IN/OR condition like in relational databases. If I have the following document in my collection, I want to read all "events.event" in ('user','bot')

{_id: 1,
sender_id:100,
"events" : [
            {
                    "event" : "action",
                    "timestamp" : 1619463803.7244627,
                    "name" : "abc1"
            },
 {
                    "event" : "user",
                    "timestamp" : 1619463803.7244627,
                    "name" : "abc2"
            },
 {
                    "event" : "bot",
                    "timestamp" : 1619463803.7244627,
                    "name" : "abc3"
            }

}

I used the following query but it only works for ONE event at a time. Can this be modified to consider event = 'user' or event = 'bot' ? And can we also project events.event and events.timestamp along with this elemMatch; all in one go?

db.conversations.find(
{"events.event": "bot"}, 
{_id: 0, sender_id:1, events: {$elemMatch: {event: "bot"}}});
2
  • no, that returns all the array objects and not just the one with event= bot Commented Apr 29, 2021 at 8:59
  • You can use the $filter aggregation expression operator in your projection. Commented Apr 29, 2021 at 9:27

1 Answer 1

2

you have lots of options

the simplest one that simulates what you have in mind about SQL queries with IN operator

db.putCollectionNameHere.aggregate([
  { $match: { _id: 1 } },
  { $unwind: '$events' },
  { $match: { 'events.event': { $in: ['user', 'bot'] } } },
]);

about $unwind documentation says

$unwind

Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I tried the above query step-by-step on MongoDB Compass aggregation pipeline and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.