【问题标题】:Mongoose - find all documents whose array property contains a given subset?Mongoose - 查找其数组属性包含给定子集的所有文档?
【发布时间】:2014-06-04 05:34:20
【问题描述】:

我有一个基于以下架构的(简化的)模型:

schema = mongoose.Schema({
    foo: { type: String },
    bars: [{ type: String }]
});
model = mongoose.model ('model', schema);

并且我想创建一个 API 来返回包含所有“条”的所有文档,这些“条”以逗号分隔列表的形式提供。所以我有:

exports.findByBars = function (req, res) {
  var barsToFind = req.body.bars.split(',');
  // find the matching document
};

Mongoose 是否为此提供了 API,或者是否有我可以传递给 Model#find 的查询参数来获得此功能?如果它的 bar 属性包含 barsToFind 数组中的所有值,我只希望返回一个文档。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    有多种方法可以构建您的查询来执行此操作,方法因您的 mongodb 服务器版本而异。所以从你的代码开始:

    对于 MongoDB 2.6 及更高版本,使用$all 运算符:

    model.find({
        "bars": { "$all": barsToFind }
    },
    

    虽然该运算符在以前的版本中确实存在,但它的行为不同,因此您实际上需要生成一个 $and 语句来显式匹配每个条目:

    var andBars = [];
    
    barsToFind.forEach(function(bar) {
        andBars.push({ "bars": bar })
    });
    
    model.find({
        "$and": andBars
    },
    

    两者都确保您只匹配包含您指定的数组中所有条目的文档,只是 MongoDB 2.6 可用的语法更好一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 2015-09-02
      相关资源
      最近更新 更多