1

I am building an application using MongoDB 4 / Mongoose 5.

I have a collection 'records' with an array of subdocuments 'Items'.

{
  RecordID: 1,
  Items: [
    { 
      Title: 'Example Title 1',
      Description: 'Example Description 1',
    },
    { 
      Title: 'Example Title 2',
      Description: 'Example Description 2',
    }
  ]
}

I am building a dynamic query generator that creates MongoDB expression operators based on a UI query builder. The dynamic query builder is building the MongoDB expressions correctly. However, the expressions are not working as expected when querying an array of subdocuments.

Question: Why is this expression not working for the nested array of subdocuments 'Items'?

This query works correctly.

db.records.find({ 'Items.Title': { $eq: 'Example title 1'} })

This same query as an expression is not returning any results.

db.records.find({ '$expr': { '$and': [ { '$eq': [ 'Items.Title', 'Example title 1' ] } ] }})

Also tried this:

db.records.find({ '$expr': { '$and': [ { '$eq': [ '$Items.Title', 'Example title 1' ] } ] }})

UPDATE: The query will work if updated to use $elemMatch instead. However, I need to use $expr because I am building nested queries using multiple and/or conditions which are constructed using the $expr operator. Is there any way to get this to work using $expr?

1 Answer 1

2

Use $elemMatch instead:

db.records.find({
    "Items" : {"$elemMatch" : {"Title" : "Example title 1"}}
})

Hope this helps.

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

1 Comment

Thanks! The query will work if updated to use $elemMatch instead. However, I need to use $expr because I am building nested queries using multiple and/or conditions which are constructed using the $expr operator. Is there any way to get this to work using $expr?

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.