【问题标题】:formatted response for find query mongo查找查询 mongo 的格式化响应
【发布时间】:2021-01-23 16:41:30
【问题描述】:

我有记录:

{
  "name" : "user",
  "number":"09xxxxxxx21",
  "pc" : [{
      "pcId" : "1",
      "pcName" : "Lenovo",
      "pcOwner" : "user1",
      "using" : true
    }, {
      "pcId" : "2",
      "pcName" : "Lenovo",
      "pcOwner" : "user1",
      "using": false
    }, {
      "pcId" : "3",
      "pcName" : "Dell",
      "pcOwner" : "user1",
      "using": true
    }, {
      "pcId" : "4",
      "pcName" : "Dell",
      "pcOwner" : "user1",
      "using": true
    }
  ]}
}

使用查询 .find({'pcID':'4','pc.pcName':'Dell'}) 我得到了完整的记录,但我想记录我只有 pcName:'Dell' 的地方。

类似的东西:

{
  "name" : "user",
  "number":"09xxxxxxx21",
  "pc" : [
    {
      "pcId" : "3",
      "pcName" : "Dell",
      "pcOwner" : "user1",
      "using": true
    }, 
    {
      "pcId" : "4",
      "pcName" : "Dell",
      "pcOwner" : "user1",
      "using": true
    }
  ]}
}

或者只有那两个对象。

【问题讨论】:

  • 任何查询都可以得到预期的输出?

标签: mongodb mongoose mongodb-query


【解决方案1】:

$filter 就是你要找的。​​p>

您可以在[aggregate][1] 中使用它

  • 使用$match,您可以在集合中选择所需的文档

  • 然后添加 $filter 过滤列表

db.collection.aggregate([
  {
    "$match": {
      "pcID": "4"
    }
  },
  {
    $project: {
      pc: {
        $filter: {
          input: "$pc",
          as: "pc",
          cond: {
            $eq: [
              "$$pc.pcName",
              "Dell"
            ]
          }
        }
      }
    }
  }
])

试试here

【讨论】:

  • 当我将值从“Dell”更改为“Lenovo”时,它给出了空白数组。
  • 哦,是的。我用 $gt 而不是 $eq ...我修复了它
【解决方案2】:

你可以使用聚合

db.collection.aggregate([
  {
    "$match": {
      "name": "user",
      "pc.pcName": "Dell"
    }
  },
  {
    "$project": {
      "name": 1,
      "number": 1,
      "pc": {
        "$filter": {
          "input": "$pc",
          "as": "pc",
          "cond": {
            "$eq": [
              "$$pc.pcName",
              "Dell"
            ]
          }
        }
      }
    }
  }
])

【讨论】:

  • 你能解释一下投影部分吗?
  • 是的。我们基本上是在投影结果中需要的所有字段。 name: 1, number: 1 告诉投影在结果中包含这些字段。由于我们只需要从pc 数组中选择的对象,我们使用$filter 运算符告诉数据库我们需要投影pc 数组中的哪些对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多