【问题标题】:Find MongoDB docs where all sub-docs match criteria查找所有子文档都符合条件的 MongoDB 文档
【发布时间】:2018-08-22 08:58:47
【问题描述】:

我有一些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 有点陌生,所以甚至确定从哪里开始。

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

尝试使用$not包裹{ "$gt" : 0 }

> 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 } 上的索引。

【讨论】:

  • 我复制了你的数据,db.products.find({"variations.quantity": { "$not" : { "$gt" : 0 } } }) 似乎要为我退回所有三种产品。可能是因为它们都包含零数量的变体,而不是退回的产品只有零数量的变化
  • 嗯,实际上,当我完全复制您的数据时,它似乎可以工作,但我的数据有点不同,所以这是我的错。结果我没有使用子文档,而是链接到其他文档(不确定正确的术语是什么)。但我的产品架构看起来更像:{name:String, variations:[{type:Schema.ObjectId, ref:'ProductVariation'}]}
  • 看起来您正在使用 Mongoose (mongoosejs.com/docs/populate.html) 的填充功能。我会玩弄它,看看我能想出什么。
猜你喜欢
  • 2017-04-24
  • 2020-07-25
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 2019-12-30
  • 2023-03-30
  • 2015-12-15
相关资源
最近更新 更多