MongoDB expression to query array of subdocuments

时光总嘲笑我的痴心妄想 提交于 2019-12-24 10:56:42

问题


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:


Use $elemMatch instead:

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

Hope this helps.



来源:https://stackoverflow.com/questions/57258776/mongodb-expression-to-query-array-of-subdocuments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!