mongoose查询子文档或为空

时间:2014-02-20 14:50:20

标签: node.js mongodb mongoose nosql

我有以下型号

var schema = new Schema({
    type: String,
    accounts: [{ type: ObjectId, ref: "Account", index: 1 }],
    accountTypes: [String],
    headline: String,
    contents: String,
    date: { type: Date, "default": Date.now }
});

我需要一个基于帐户的查询,为我提供与其中一个匹配的所有文档。

  • accounts.length === 0 && accountTypes.length === 0
  • accounts.length === 0 && accountTypes.indexOf(account.type) !== -1
  • accounts.indexOf(account.type) !== -1 && accountTypes.length === 0

以尽可能少的步骤执行此查询的最佳方法是什么?我可以在一个查询中执行此操作吗?怎么样?

我知道我可以将这些查询堆叠在一起,但感觉不太高效。

这是我到目前为止所拥有的,但我不确定它是否有用。

Notification.find({
    $or: [
        { $and: [{ $where: "this.accounts.length === 0" }, { $where: "this.accountTypes.length === 0" }] },
        { $and: [{ $where: "this.accounts.length === 0" }, { accountTypes: account.type }] },
        { $and: [{ $where: "this.accountTypes.length === 0" }, { accounts: account._id }] }
    ]
}, function (err, notifications) {
    // stuff
});

1 个答案:

答案 0 :(得分:4)

试试这个:

Notification.find({
    $or: [
        { $and: [{ accounts: { $size: 0 }, { accountTypes: {$size: 0 }] },
        { $and: [{ accounts: { $size: 0 }, { accountTypes: account.type }] },
        { $and: [{ accountTypes: { $size: 0 }, { accounts: account._id }] }
    ]
}, function (err, notifications) {
    // stuff
});

修改

甚至更短(感谢JohnnyHK提示)

Notification.find({
    $or: [
        { accounts: { $size: 0 }, accountTypes: { $size: 0 } },
        { accounts: { $size: 0 }, accountTypes: account.type },
        { accountTypes: { $size: 0 }, accounts: account._id }
    ]
}, function (err, notifications) {
    // stuff
});