【问题标题】:Return matched documents from the array [duplicate]从数组中返回匹配的文档[重复]
【发布时间】:2018-06-13 16:12:14
【问题描述】:

我目前正在尝试在 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)
        }
    ]
}
}

【问题讨论】:

  • 请发布您的样本集
  • 添加了样本集合

标签: arrays mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要在这里使用$filter aggregation ,它只是从数组中消除不匹配的文档

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

【讨论】:

    【解决方案2】:

    试试这个代码:

    db.collectionName.find({"punishdata.Entrys.id": "ZhU76Ta" })
    

    【讨论】:

    • 只返回 0 条目,我想获取数组中的所有条目,以便匹配采石场
    • 你有更多相同id的值ZhU76Ta吗?
    • @NetherGames-de 当前答案是正确的。我确定你做错了什么......
    • @Serdar 是的,ID 为 ZhU76Ta 的数据中有更多值,我想获取所有这些值
    • @NetherGames-de 然后试试这个:db.collectionName.find({"punishdata.Entrys.id": {$all:["ZhU76Ta"] }})
    猜你喜欢
    • 2019-01-16
    • 2021-08-20
    • 2021-01-09
    • 1970-01-01
    • 2019-07-09
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多