Find documents that contain the object id in an array (Mongodb)

197 Views Asked by At

I am working on a node project and can't figure out how to use the find() function on an array of object ids.

Here is an example of a document from my mongodb database:

{
  "_id": {
    "$oid": "6515923586714e6ae70be0a9"
  },
    "managers": [
    {
      "$oid": "6515a0ba76e7e07f68160ef5"
    },
    {
      "$oid": "6515a0d35c2d7cad9b070e64"
    }
  ]
}

I tried this code.

router.get("/processes/formanager/:id",async(req,res) =>{
  let processCollection = await db.collection("processes");
  let query, processes, cursor;

  try{query = {"$elemMatch": new ObjectId(req.params.id)};}
  catch(err){res.status(404).json({error: "Not a valid id"}); return;}

  try{
    cursor = await processCollection.find({managers: query});
    
    // iterate over cursor once
    processes = await cursor.next();
  }
  catch(err){
    console.log(err);
    res.status(404).json({error: "No processes assigned to this manager"}); 
    return;}
  res.status(200).json({ processes })

});

I am expecting to get this document and others that meet the citeria. If i can manage to get the first result, I will iterate over the cursor.

The result I get is null processes (when code is run as above) OR I get the error "$elemMatch needs an object" when I remove the "" around $elemMatch.

2

There are 2 best solutions below

3
ABDULLOKH MUKHAMMADJONOV On

to search from an array of simple values (non array, non object) you can directly run query this query:

query = {"managers": new ObjectId('6515a0ba76e7e07f68160ef5')};
cursor = await processCollection.find(query)

to search from an array of objects you should use $elemMatch. Here is an example:

// sample data
[
    {
        _id: '6515a0ba76e7e07f68160ef5',
        name: "John",
        surname: "Doe"
    },
    {
        _id: '6415a0ba76e7e07f6816a125e',
        name: "Alex",
        surname: "Gerard"
    }
]

query = {"$elemMatch": {_id: new ObjectId('6515a0ba76e7e07f68160ef5')}};
cursor = await processCollection.find({managers: query})
// or
query = {"$elemMatch": {name: "Alex"}};
cursor = await processCollection.find({managers: query})
0
Gert Vermeulen On

A colleague of mine gave me the correct code

  1. $elemMatch / $in should not be in quotation marks
  2. The query inside of $elemMatch / $in needed to be inside angled braces [] for my case

cursor = await processCollection.find({managers: {$in:[new ObjectId(req.params.id)]}})