I have a collection of data stored in MongoDB structured like this:
users: {
{
user_id: 1000,
activities: [
{id: 1, activity: 'swimming'},
{id: 2, activity: 'running'},
{id: 3, activity: 'biking'},...
]
},...
}
My goal is to retrieve the activity document that corresponds to a specific ID. For instance, if I search for {id: 1}
, I expect to receive {id: 1, activity: 'swimming'}
. Currently, I'm using
findOne({activities: {$elemMatch: {id: 1}}})
, but it returns the entire user document along with all the activities.
The code snippet I'm working with is:
id = req.body.queryID;
db.collection('users').findOne({activities: {$elemMatch: {id}}})
.then((document) => {
console.log(document);
// additional code here
});
I've also attempted to use aggregate()
and
findOne({}, {activities: {$elemMatch: {id}}})
for querying, but I haven't been successful in resolving it.
According to db.version()
, I am currently running MongoDB version 4.4.8. Any assistance on this matter would be greatly appreciated!