1

我有一个带有嵌入式文档数组的模型。这是设计使然,因为我们经常(几乎总是)将根文档与嵌入式文档一起查询。

var SubsetSchema = new mongoose.Schema({
    number: {
        type: Number,
        index: true,
        unique: true,
    },
    name: String,
});

var RootSchema = new mongoose.Schema({
    name: String,
    subsets: [SubsetSchema],
});

mongoose.model('collection', RootSchema);
var Root = module.exports = mongoose.model('collection');

使用以下方法查找单个子集文档不是问题:

Root.findOne({'subsets.number': 3}, {_id: 0, 'subsets.$': 1}, ...);

但是,当我需要找到多个子集文档(在我们的例子中使用正则表达式)似乎是不可能的:

Root.find({'subsets.name': /regex/i}, {_id: 0, 'subsets.$': 1}, ...);

它给出了以下错误:

error: {
    "$err" : "positional operator (subsets.$) requires corresponding field in query specifier",
    "code" : 16352
}

在这种情况下我会怎么做?将 Schema 拆分为两个集合不是一种选择,因为这会破坏我们在其他更频繁的查询上的性能。

4

1 回答 1

3

这可以在 mongo shell 中重现:

> db.xx.find().pretty()
{
    "_id" : ObjectId("51610020672afd480ccfb9c4"),
    "name" : "any",
    "subsets" : [
        {
            "number" : 3,
            "name" : "aba"
        },
        {
            "number" : 4,
            "name" : "aka"
        }
    ]
}
> // works as expected:
> db.xx.find({"subsets.number": 3},{_id:0, "subsets.$":1})
{ "subsets" : [ { "number" : 3, "name" : "aba" } ] }
> // does not work
> db.xx.find({"subsets.name": /k/},{_id:0, "subsets.$":1})
error: {
    "$err" : "positional operator (subsets.$) requires corresponding field in query specifier",
    "code" : 16352
}

但这有效!

> db.xx.find({"subsets": {$elemMatch:{name:/k/}}},{_id:0, "subsets.$":1})
{ "subsets" : [ { "number" : 4, "name" : "aka" } ] }

@AlexKey:我已经相应地更新了你的 Jira SERVER-9028

于 2013-04-07T05:56:41.470 回答