查找所有子文档均符合条件的MongoDB文档

时间:2018-08-21 23:55:02

标签: mongodb mongoose

我有一些Product个文档,每个文档都包含ProductVariation个子文档的列表。我需要查找所有Product个文档,其中 ALL 个孩子的ProductVariation文档的数量为零。

模式如下:

var Product = new mongoose.Schema({
    name: String,
    variations: [ProductVariation]
});

var ProductVariation = new mongoose.Schema({
    type: String,
    quantity: Number,
    price: Number
});

我对mongodb有点陌生,所以即使确定从这里开始。

1 个答案:

答案 0 :(得分:1)

尝试使用{ "$gt" : 0 }周围的$not

> db.products.find()
{ "_id" : ObjectId("5b7cae558ff28edda6ba4a67"), "name" : "widget", "variations" : [ { "type" : "color", "quantity" : 0, "price" : 10 }, { "type" : "size", "quantity" : 0, "price" : 5 } ] }
{ "_id" : ObjectId("5b7cae678ff28edda6ba4a68"), "name" : "foo", "variations" : [ { "type" : "color", "quantity" : 2, "price" : 15 }, { "type" : "size", "quantity" : 0, "price" : 5 } ] }
{ "_id" : ObjectId("5b7cae7f8ff28edda6ba4a69"), "name" : "bar", "variations" : [ { "type" : "color", "quantity" : 0, "price" : 15 }, { "type" : "size", "quantity" : 1, "price" : 5 } ] }

> db.products.find({"variations.quantity": { "$not" : { "$gt" : 0 } } })
{ "_id" : ObjectId("5b7cae558ff28edda6ba4a67"), "name" : "widget", "variations" : [ { "type" : "color", "quantity" : 0, "price" : 10 }, { "type" : "size", "quantity" : 0, "price" : 5 } ] }

它也可以利用{ "variations.quantity" : 1 }上的索引。