简体   繁体   中英

MongoDB expression to query array of subdocuments

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 ?

Use $elemMatch instead:

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM