skip to Main Content

I want to query a collection "chat" whose documents have an array field "participants". This array has always two objects with the properties id and name. I want to find the document that matches the two ids of the embeded objects. For example, I want to find the following document in which the ids are "1" and "2".


  //chat 
//find ids 1 and 2. 
//this is the document that I am looking for and should be returned. 
{
   _id : ytyutu876788
     participants : [ {id : 1, name : Murray}, {id : 2, name : Pier} ]
}
//In this document id 1 is present but not together with id 2.
{
   _id : d6t6d6tdt6
     participants : [ {id : 1, name : Murray}, {id : 3, name : Gustav} ]
}

The query that I have tried to use so far is the following which returns an empty array even though I am sure that the document that I want to find exists in the collection so I know that it is the query what I am doing wrong:

try {
            const userId = req.body.userId
            const friendId = req.body.friendId
            console.log(userId)
            console.log(friendId)
            await client.connect()
            const query = await client.db('instagram_clone').collection('chat').find(
                {"participants.id" : {userId, friendId}}
            ).toArray()
            console.log(query)

2

Answers


  1. Chosen as BEST ANSWER

    This another query that does the job, in which I used the $elemmatch operator.

    const firstQuery = await client.db('instagram').collection('chat').find({
      participants : {
        $all: [
          {
            $elemMatch: {
              id: friendId
            }
          }, {
            $elemMatch: {
              id: userId
            }
          }
        ] 
      }
    }).toArray();
    

  2. You may use $all operator like

    const query = await client.db('instagram_clone')
                                .collection('chat')
                                .find({"participants.id": {$all:[userId, friendId]}})
                                .toArray();
    

    Or you may like to use $and operator like

    const query = await client.db('instagram_clone')
                                .collection('chat')
                                .find({$and :[{"participants.id": userId}, {"participants.id": friendId}]})
                                .toArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search