【问题标题】:Using the moongoose find() method to query items within arrays使用 mongoose find() 方法查询数组中的项目
【发布时间】:2020-02-02 19:00:30
【问题描述】:

这是我的架构的样子。

const CollectionSchema = new mongoose.Schema({
  since: Date,
  batch_id: Number,
  info: [InfoSchema],
  items: [ItemSchema]
});

const ItemSchema = new mongoose.Schema({
  name: String,
  price: Number,
  url: String
});

我正在寻找特定商品名称的 Collection batch_id、Collection info、Item price、Item url。请注意,集合有一个项目数组,我们可以假设项目名称是不同的。下面的查询(我认为)应该返回 Collection info + batch_id 用于包含名称为“lego”的任何项目的集合。

Collections.find(
  { "items.name": 'lego' },
  { info: 1, batch_id: 1 }
)
   .where("since")
   .gt(minutesAgo)

我想在回复中包含商品价格和商品网址。我将如何更改 find() 调用以返回该数据?同样,添加项目:1 将添加所有项目(但我正在寻找匹配项目的价格和网址)。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以使用$ 仅返回所选项目,但不幸的是,在这种情况下,您无法选择要返回项目的哪些字段(您需要为此使用聚合框架):

    Collections.find(
      { "items.name": "lego" },
      { info: 1, batch_id: 1, "items.$": 1 }
    )
    

    上面的查询将只返回第一个匹配项,而不是全部。

    【讨论】:

      【解决方案2】:

      您可以将items.priceitems.url 放入选择查询中以包含缺失的字段。

      Collections.find(
        { "items.name": 'lego' },
        { info: 1, batch_id: 1, "items.price": 1, "items.url": 1 }
      )
         .where("since")
         .gt(minutesAgo)
      

      【讨论】:

      • 这将返回集合中每个项目的价格和网址(而不仅仅是选定的项目)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2021-03-03
      • 2019-10-27
      相关资源
      最近更新 更多