0

我想加入一个集合,然后在 mongodb 中找到。

这是我的收藏:

颜色:

{id: 1, color: 'red'}
{id: 2, color: 'blue'}

价格:

{price_id: 1, price: 4}
{price_id: 2, price: 5}

如何找到价格为 5 美元的颜色?

这是我的解决方案(不起作用):

db.collection('colors').aggregate([
    {
        $lookup:
            {
                from: 'prices',
                localField: 'id',
                foreignField: 'price_id',
                as: 'info'
            },
        $match:
            {
                price: 5
            }
    }
]).toArray((res, err) => {
    if (res) {
        console.log(res);
    } else {
        console.log(err);
    }
})
4

2 回答 2

1

如果您有 MongoDB 3.6 或更高版本

db.colors.aggregate([
  { $lookup:{
     from: "prices",
     let: { id: "$id"},
     pipeline: [
        { $match: { 
            $expr: {
              $and:[ { $eq: ["$price_id", "$$id"]}, { $eq: ["$price", 5] }]
            }
        }},
      ],
      as: "info"
  }}
])
于 2019-09-09T18:15:33.140 回答
0

是你 $match 没工作造成的!

价格在 info 字段中,它是数组中的内部字段。

join后的数据是这样的

{ "_id" : ObjectId("5d79125fcc36fb6c276f2edd"), "id" : 1, "color" : "red", "info" : [ { "_id" : ObjectId("5d79128ccc36fb6c276f2edf"), "price_id" : 1, "price" : 4 } ] }
{ "_id" : ObjectId("5d79125fcc36fb6c276f2ede"), "id" : 2, "color" : "blue", "info" : [ { "_id" : ObjectId("5d79128ccc36fb6c276f2ee0"), "price_id" : 2, "price" : 5 } ] }

你可以改变你的 $match 功能

 db.getCollection("colors").aggregate(
[
{$lookup: {  from: 'prices', 
              localField: 'id',
              foreignField: 'price_id',
              as: 'info'}
          },
{$unwind :"$info"},
{$match:{"info.price":5}}
]
)

于 2019-09-11T15:41:20.690 回答