【问题标题】:MongoDB sort documents using another collection arrayMongoDB 使用另一个集合数组对文档进行排序
【发布时间】:2023-04-09 01:33:01
【问题描述】:

我会尽力解释我想要达到的目标。

(注意:_id 是自动生成的)

让我们从我要查询的架构开始

cocktail: Schema = 
    name: { type: String },
    ingredients: [{ type: ObjectId, ref: 'ingredient', required: true }]

简单地说,名称是鸡尾酒的名称,成分是构成鸡尾酒的元素。

为简单起见,这是成分模式

ingredient: Schema = 
    name: { type: String }

简单干净。

假设我有一个用户集合,用户可以在其中选择自己喜欢的成分。用户的成分可以为空。

user: Schema = 
    name: { type: String },
    preferredIngredients: [{ type: ObjectId, ref: 'ingredient' }]

现在的问题是:是否可以通过用户最喜欢的成分来查询鸡尾酒系列?

我试过了(me 是以前的查询来查找用户)

db.cocktails.find({ ingredients: { $in: [me.preferredIngredients] }})

但它从不返回数据。我对 mongo 或 mongooose 进一步挖掘的经验不是很好

请帮忙!

【问题讨论】:

  • 假设一切正常 - { $in: [me.preferredIngredients] } - 尝试去掉方括号。 me.preferredIngredients 已经是一个数组,您正在以这种方式创建一个数组数组。
  • @Anton 谢谢。我没想到。

标签: mongodb mongoose


【解决方案1】:

是的,有可能,你应该使用$lookup mongo version 3.6+ 语法:

db.users.aggregate([
   {
     $lookup: {
       from: "cocktails",
       let: { ingredients: "$preferredIngredients" },
       pipeline: [ 
            { $match:
                 { $expr:
                    { $setIsSubset : ["$ingredients", "$$ingredients"]},
                 }
              }
       ],
       as: 'matched_cocktails'
     }
   }
])

【讨论】:

  • 嗯,这给了我所有用户和所有与他们喜欢的成分相匹配的鸡尾酒。我将以您的代码为例来使我的代码正常工作。谢谢,你太棒了。
  • 没问题,显然您可以在查找之前轻松添加匹配阶段以仅过滤相关用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多