📌  相关文章
📜  如何过滤 mongodb 中的填充数据 - Javascript (1)

📅  最后修改于: 2023-12-03 15:38:55.972000             🧑  作者: Mango

如何过滤 MongoDB 中的填充数据 - JavaScript

在 MongoDB 中,使用填充数据的目的是为了避免多次查询以获取相关字段的数据,提高查询效率。但是有时候我们需要过滤掉填充的数据,以便只返回我们需要的数据。本篇文章将介绍如何使用 JavaScript 过滤 MongoDB 中的填充数据。

填充数据

填充数据使用 $lookup 操作符,语法如下:

db.collection.aggregate([
  {
    $lookup: {
      from: "collectionToJoin",
      localField: "fieldToJoinOn",
      foreignField: "_id",
      as: "aliasToOutput"
    }
  }
])

其中,collectionToJoin 为需要连接的集合名称,fieldToJoinOn 为需要连接的字段,_id 为目标集合的 _id 字段。as 为填充数据后输出的字段名称。

过滤填充数据

可以使用数组的 map() 方法过滤掉填充数据,具体代码如下:

db.collection.aggregate([
  {
    $lookup: {
      from: "collectionToJoin",
      localField: "fieldToJoinOn",
      foreignField: "_id",
      as: "aliasToOutput"
    }
  },
  {
    $project: {
      desiredFields: { $filter: {
        input: "$aliasToOutput",
        as: "field",
        cond: { $ne: [ "$$field", null ] }
      }},
      otherFields: 1
    }
  }
])

使用 $project 操作符对填充的数据进行过滤,desiredFields 为我们需要输出的字段,otherFields 为其他需要输出的字段。

其中,$filter 操作符用于根据条件过滤数组元素。input 为输入的数组,as 为数组中的每一个元素,在此例中即为填充的数据,cond 为过滤条件,此处为只输出不为 null 的数组元素。

总结

本文介绍了如何使用 JavaScript 过滤 MongoDB 中的填充数据。通过使用 $project 操作符和 $filter 操作符,可以方便地过滤掉填充的数据,以输出我们需要的数据。