1

I have a MongoDB object with an array of objects inside it, structured as

{
    otherInfo: String,
    invited: [{
        code: String,
        email: String
    }],
    moreInfo: String
}

I'm trying to find a specific object in that array with a specific code, and then get the email associated with that code.
I have tried .find({ invited: { $all: [{ code: 1234567890 }]}}) but it didn't return anything. I have tried other variations on it none none of them seem to have worked

2 Answers 2

1

You can use the $elemMatch to solve your query

The $elemMatch operator limits the contents of an field from the query results to contain only the first element matching the $elemMatch condition.

Try this

db.collection.find({ invited: { $elemMatch: { code: 1234567890 } } } )
Sign up to request clarification or add additional context in comments.

Comments

1

Try like this

app.get('/', async (req, res) => { //change with your endpoint code
 const findCode = await Models.find({}) //change name of your models
 const result = findCode.invited.filter(item => {
   item.code ==  '1234567890'
 })
 console.log(result);
})

Or try with this:

Models.find().elemMatch("invited", {"code":"1234567890"}).exec((err,result)=>{
    console.log(result);
}) //change your Models name 

1 Comment

This makes the database return all its items. It's a working solution though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.