2

这是单个文档:

{
   _id: "...",
   firstName: "john",
   lastName:"Doe",
   cars: [
       {
           "_id": "...",
           "carName": "BMW",
           "carModel": "330",
           "carColor": "silver"
       },
       {
           "_id": "...",
           "carName": "Lexus",
           "carModel": "IS300",
           "carColor": "white"
       },
       {
           "_id": "...",
           "carName": "LADA",
           "carModel": "2106",
           "carColor": "blue"
       }
   ]
}

我想只选择约翰的宝马的“carColor”。像这样的东西:

db.persons.findOne(
        { "firstName": "John", "cars.carName": "BMW" },
        { "_id": 0, "cars.$.carColor": 1 }
      );

但是这个查询返回完整的对象,如下所示:

{
    cars: [
      {
         "_id": "...",
         "carName": "BMW",
         "carModel": "330",
         "carColor": "silver"
      }
}

我已经尝试了不同的查询,没有.$。象征:

db.persons.findOne(
            { "firstName": "John", "cars.carName": "BMW" },
            { "_id": 0, "cars.carColor": 1 }
          );

此版本仅返回“carColor”属性,但不过滤“carName”。像这样:

{
   cars: [
       {
          "carColor": "silver"
       },
       {
          "carColor": "white"
       },
       {
          "carColor": "blue"
       }
   ]
}

有任何想法吗?

4

3 回答 3

2

为什么它不起作用?

{“名字”:“约翰”,“cars.carName”:“宝马”}

意思是'名字是 john 并且在汽车数组中至少有一个条目,其中 carName 是“BMW”'。但它返回完整的文档,没有过滤数组。

{ "_id": 0, "cars.carColor": 1 }

不要投影_id,而是投影汽车数组所有条目的carColor。

解决方案

实际上,您无法使用 find 和 projection 方法准确地实现您想要的。您可以做的更好的是添加$ 投影运算符,如下所示:

db.collection.find({
  firstName: "john",
  "cars.carName": "BMW"
},
{
  _id: 0,
      "cars.$": 1
    })

**RESULT**

[
  {
    "cars": [
      {
        "_id": "...",
        "carColor": "silver",
        "carModel": "330",
        "carName": "BMW"
      }
    ]
  }
]

但是这种方法有缺点:

  • 你得到整个数组条目,而不仅仅是你想要/需要的颜色
  • 它只返回第一个匹配的条目:如果 john 有 2 辆宝马,则只返回一个。

更好的解决方案

幸运的是,MongoDB 提供了另一种方法来实现这一点,即聚合框架和$filter运算符:

db.collection.aggregate([
  {
    $match: {
      firstName: "john"
    }
  },
  {
    $project: {
      cars: {
        $filter: {
          input: "$cars",
          as: "cars",
          cond: {
            $eq: [
              "$$cars.carName",
              "BMW"
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      "colors": "$cars.carColor"
    }
  }
])

你可以在这里试试。

编辑:其他解决方案

你也可以试试这个,放松/分组阶段:

db.collection.aggregate([
  {
    $match: {
      firstName: "john"
    }
  },
  {
    $unwind: "$cars"
  },
  {
    $match: {
      "cars.carName": "BMW"
    }
  },
  {
    $group: {
      "_id": null,
      colors: {
        $push: "$cars.carColor"
      }
    }
  }
])
于 2018-10-10T13:55:05.887 回答
0

如果您知道数组中的“BMW”值不超过一个,那么这是一种使用单个$project阶段获取结果的方法:

db.getCollection('collection').aggregate([{
    $match: {
        "firstName": "john"
        /* for performance reasons, you may want to include the following line which, however, is not required */
        /* this makes sense if you have lots of "john"s with different sets of cars in your database */
        , "cars.carName": "BMW" // this will use an index on "cars.carName" if available
    }
}, {
    $project: {
        _id: 0, // do not return the _id field
        color: {
            $reduce: { // transform the filtered input array
                "input": {
                    $filter: { // remove all non-"BMW" cars from the "cars" array
                        input: "$cars",
                        as: "car",
                        cond: { $eq: [ "$$car.carName", "BMW" ] }
                    }
                },
                "initialValue": null,
                "in": "$$this.carColor" // just return the color value, nothing else
            }
        }
    }
}])
于 2018-10-10T20:23:42.190 回答
0
db.persons.find({
  firstName: 'john',
  cars: {
    $elemMatch: {
      carName: 'BMW'
    }
  }
},
{
  'cars.$': 1
})
于 2018-10-10T14:34:43.980 回答