【问题标题】:Mongodb search in Document and subDocument through single queryMongodb通过单个查询在Document和subDocument中搜索
【发布时间】:2021-04-07 05:36:02
【问题描述】:

我有一个包含数组子文档的文档

我需要通过单个查询搜索文档和子文档

我只需要子文档数组数据的结果,通过条件

样本数据 [2 个文档]

{
  _id : ObjectId("512e28984815cbfcb21646a7"),
  name: David,
  list: [
    {
      sport: basketball,
      score: 100
    },
    {
      sport: cricket,
      score: 30
    }
    {
      sport: rugby,
      score: 100
    }
    ]
},

{
  _id : ObjectId("879e28664815cbfcb21622g9"),
  name: Shawn,
  list: [
    {
      sport: basketball,
      score: 100
    },
    {
      sport: cricket,
      score: 50
    }
    {
      sport: rugby,
      score: 20
    }
    ]
}

预期结果

大卫得分为 100 的游戏列表

  • 文档查询name = David
  • 子文档查询score = 100

响应:[篮球、橄榄球]


查询已尝试,但结果为 NULL

findOne({name:'David', "list.score": 100})

【问题讨论】:

  • 试试findOne({name:'David', list: { $elemMatch: {score: 100} })
  • @WernfriedDomscheit 这给了我整个文档.. 列表也包含 !=100 分

标签: database mongodb mongoose subdocument


【解决方案1】:

要获得大卫得分为 100 的游戏列表,您应该这样做:

const user = await User.findOne({name:'David'}) 
if (user){
    const games = user.list.filter(el => el.score === 100)
    console.log(games)
}

【讨论】:

    【解决方案2】:

    您可以使用聚合管道。

    • 名称使用简单的$match
    • 对于数组,使用$filter 函数

    会是这个:

    db.collection.aggregate([
      { $match: { name: "David" } },
      {
        $set: {
          list: {
            $filter: {
              input: "$list",
              cond: {$eq: ["$$this.score", 100] }
            }
          }
        }
      }
    ])
    

    【讨论】:

    • 在 cond 时会是双倍的 $ 吗??
    • 是的,$$this 是默认变量名。见$filter()Variables in Aggregation Expressions
    • 这在我的 MongoDB 指南针上工作.. 但是当我把它放在代码中.. 没有给出结果!!!
    • 你能建议我条件吗,如果不是分数,我会用 scoreId
    • ScoreId 将是 ObjectId ..在 ObjectId 比较的情况下 $eq 不工作
    【解决方案3】:

    使用elemMatch 投影运算符来限制数组的元素:

    await User.findOne({name:'David', 'list.score': 100}).select({list:{$elemMatch:{score:100}})
    

    该示例文档似乎没有在字符串周围显示引号。

    请注意,{score:100} 仅在值为数字时才匹配,即它不会匹配 {sport: "basketball", score:"100"}

    【讨论】:

    • 感谢您的回答...但这只会返回一条子文档记录。我需要数组的所有元素都等于 100
    【解决方案4】:

    只是对已接受答案的充值

    也可以从 MongoDB 指南针生成匹配和设置聚合代码

    Compass 的聚合选项卡 --> 导出到语言按钮

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2022-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多