简体   繁体   English

猫鼬-查找其数组属性包含给定子集的所有文档?

[英]Mongoose - find all documents whose array property contains a given subset?

I have a (simplified) model based on the following schema: 我有一个基于以下架构的(简化)模型:

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

and I want to create an API to return all documents that contain all of the 'bars' which are provided in a comma separated list. 并且我想创建一个API以返回包含以逗号分隔的列表提供的所有“栏”的所有文档。 So I have: 所以我有:

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

Does Mongoose provide an API for this or is there a query param I can pass to Model#find to get this functionality? Mongoose是否为此提供了API,或者是否可以将查询参数传递给Model#find以获取此功能? I only want a document to be returned if its bar property contains all of the values in the barsToFind array. 我只希望文档的bar属性包含barsToFind数组中的所有值时barsToFind

There are ways to structure your query to do this, the approaches are different depending on your mongodb server version. 有多种方法可以构造查询来执行此操作,具体方法取决于您的mongodb服务器版本。 So following on from your code: 因此,从您的代码继续:

For MongoDB version 2.6 and above, use the $all operator: 对于MongoDB 2.6及更高版本,请使用$all运算符:

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

And though the operator does exist for previous versions, it behaves differently so you actually need to generate an $and statement to explicitly match each entry: 尽管以前版本中确实存在该运算符,但是它的行为有所不同,因此您实际上需要生成$and语句以显式匹配每个条目:

var andBars = [];

barsToFind.forEach(function(bar) {
    andBars.push({ "bars": bar })
});

model.find({
    "$and": andBars
},

Both ensure that you only match documents that contain all of the entries in the array as you have specified, it's just that the syntax available to MongoDB 2.6 is a little nicer. 两者都确保您只匹配包含指定数组中所有条目的文档,只是MongoDB 2.6可用的语法好一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM