如何使用 mongoose 对数组中数组中的元素进行查询?

栏目: mongoose教程 发布时间:2021-12-24

假设我们有一个 articles 集合,数据如下:

[{
  _id : ObjectId("61949cde03ce3143a5574da4"),
  tags: ['node', 'express'],
  columns: [{
    name: 'node'
  }, {
    name: 'express'
  }]
  ...
}, {
  _id : ObjectId("61949cde03ce3143a5574da5"),
  tags: ['node', 'node-excel'],
  columns: [{
    name: 'node'
  }, {
    name: 'excel'
  }]
  ...
}, {
  _id : ObjectId("61949cde03ce3143a5574da6"),
  tags: ['mongoose'],
  columns: [{
    name: 'mongoose'
  }]
  ...
}]
  • 查找 tags 字段包含 'node' 的 articles
Article.find({
  tags: {
    $in: 'node'
  }
}).limit(10)

Article.find({
  tags: {
    $elemMatch: {
      $eq: 'excel'
    }
  }
}).limit(10)
  • 查找 columns 字段包含 'excel' 的 articles
Article.find({
  columns: {
    $elemMatch: {
      name: 'excel'
    }
  }
}).limit(10)

本文地址:https://www.tides.cn/p_mongoose-find-array

标签: $elemMatch