MongoDB表达式查询子文档数组 [英] MongoDB expression to query array of subdocuments

查看:597
本文介绍了MongoDB表达式查询子文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB 4/Mongoose 5构建应用程序.

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',
    }
  ]
}

我正在构建一个动态查询生成器,该生成器将基于UI查询构建器创建MongoDB表达式运算符.动态查询构建器正在正确构建MongoDB表达式.但是,查询子文档数组时,这些表达式无法正常工作.

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'?

此查询正常工作.

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' ] } ] }})

也尝试过这个:

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

更新:如果将查询更新为使用$elemMatch,则该查询将起作用.但是,我需要使用$expr,因为我正在使用使用$expr运算符构造的多个和/或条件来构建嵌套查询.有什么方法可以使用$expr使其工作?

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?

推荐答案

使用 $elemMatch 代替:

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

希望这会有所帮助.

这篇关于MongoDB表达式查询子文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆