首页 > 解决方案 > 从数组中返回匹配的文档

问题描述

我目前正在尝试在 mongodb 中查询一个数组,我想在其中查找所有具有 id: " ZhU76Ta" 的字段,但是要搜索的数组在其他文档中被禁止,所以我的查询看起来像这样:{"punishdata.Entrys.0.id": "ZhU76Ta"}但是这仅查询数组中的第一个文档,我尝试过这样的事情,{"punishdata.Entrys.*.id": "ZhU76Ta" }但这也不起作用,有人知道该怎么做吗?

Document structure:
{
"_id" : ObjectId("5b212e540a975a231c85419c"),
"name" : "Starmixcraft",
"punishdata" : {
    "Entrys" : [ 
        {
            "id" : "ZhU76Ta",
            "end" : NumberLong(-2),
            "start" : NumberLong(1528901227837),
            "time" : NumberLong(-2)
        }
    ]
}
}

标签: arraysmongodbmongodb-queryaggregation-framework

解决方案


你需要在$filter aggregation 这里使用它来简单地从数组中消除不匹配的文档

db.collection.aggregate([
  {
    "$project": {
      "name": 1,
      "punishdata.Entrys": {
        "$filter": {
          "input": "$punishdata.Entrys",
          "as": "entry",
          "cond": {
            "$eq": [
              "$$entry.id",
              "ZhU76Ta"
            ]
          }
        }
      }
    }
  }
])

推荐阅读