0

I have 2 collections

Incident

{ 
     _id:...,
     suspects : [{id:...,...},{}...]
}  

and Suspect

{
    _id:...
}

The suspects in the Incident document are nested object that is not the equal to the document in collection Suspects but a subset with an id that matches the suspect in the suspects collection.

I would like to query the db, either for the incidents and to attach at the array (or create new one) with the actual documents that matches the ids or Query for suspects with attached a property that is the incident document where the suspect id exists in the array.

1 Answer 1

1

If you have the id field in the Incident collection, and that is corresponding to the actual document id in the Suspect collection, you can use the lookup operator

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

I've setup a sample code in this Mongo Playground. Let me know if you need further explanation :)

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

3 Comments

Thanks that really helpfull. I think my current problem is that the id in the suspects is a string and the _id is ObjectId
In that case you should do the following: - unwind the suspects array https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/ - use the combination of toObjectId and addFields to add a virtual field to your model containing the object id version of your stored id [docs.mongodb.com/manual/reference/operator/aggregation/… - use the lookup aggregation, using the virtual field from previous step as local field - group results by incident id

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.