Home > Mobile >  find element in array within array mongoose
find element in array within array mongoose

Time:09-26

I have this data:

[
  {
    contacts: [ [Object] ],
    _id: 614a1301a926d73628d791fe,
    username: 'erick',
    socketId: 'OB8uqmHnsGPKC3gcAAAB'
  },
  {
    contacts: [ 
       contacts: [ [Object] ],
       _id: 614a1301a926d73628d791fe,
       username: 'erick',
       socketId: 'OB8uqmHnsGPKC3gcAAAB'
    ],
    _id: 614a1306a926d73628d79204,
    username: 'tachancka',
    socketId: 'cN333_zn8r48K_0tAAAB'
  }
]

And i need to find the username of 'erick' inside 'tachancka' contacts. I have tried a few ways to do it but none of them worked for me, returning null.

For example:

User.findOne({contacts: {$elemMatch:{'username': 'erick'}}}) 

Or:

User.findOne({'contacts.username': 'erick'})

CodePudding user response:

pls refer to sample here: https://mongoplayground.net/p/Np_MdrubPgT

you may use

db.User.find({
  username: "tachancka",
  "contacts.username": "erick"
})

When you have array of objects and if you want to match all the field within object then we use $elemMatch, here in your case i feel username is not part of contacts array hence you will not use $elemMatch

  • Related