首页 > 解决方案 > 查询 mongoose 中的填充字段

问题描述

如何在我的猫鼬查询中设置此条件?
请注意,coinId 是一个填充字段

signalModel
    .find(
        {
            'coinId.Price': { $gt: 1000 }
        },
        (err, signals) => {
            if (err) throw err
            res.json(signals)
        }
    )
    .populate('coinId')

更新:

我从答案中尝试了这个查询,但我对结果不满意,因为 coin 字段是一个空数组。

let signals = await signalModel.aggregate([
    {
        $lookup: {
            from: 'Coin',
            localField: 'coinId',
            foreignField: '_id',
            as: 'coin'
        }
    },
    {
        $match: {
            type: req.query.type ?? /^(buy|sell)$/i,
            'coin.Price': { $gt: 1000 }
        }
    }
])

结果:

{
    "_id": "616eb8d2c31a52512900f56b",
    "coinId": "616e8c07ca518ef7fac3eea9",
    "type": "buy",
    "highEntryPoint": 60000,
    "lowEntryPoint": 59500,
    "stopLoss": 59000,
    "takeProfit": 60500,
    "lastPrice": 61998.1102423889,
    "status": "waiting",
    "__v": 0,
    "coin": []
}

更新2

输入示例/信号

{
"_id" : ObjectId("616eb8d2c31a52512900f56b"),
"coinId" : ObjectId("616e8c07ca518ef7fac3eea9"),
"type" : "buy",
"highEntryPoint" : 60000,
"lowEntryPoint" : 59500,
"stopLoss" : 59000,
"takeProfit" : 60500,
"lastPrice" : 61998.1102423889,
"status" : "waiting",
"__v" : 0
}

输入示例/硬币

{
"_id" : ObjectId("616e8c07ca518ef7fac3eea9"),
"Name" : "BTC",
"Price" : 61700.9584311177,
"__v" : 0
}

标签: node.jsmongodbmongoose

解决方案


首先使用$lookup然后添加条件,如下所示:

signalModel.aggregate([
{$lookup:{
from: 'Coins' // coins collection name
localField: coindId,
foreignField: _id
as: coins
}},
{
  $match:{'coins':{$ne: []}}
 }
,{
$match :{"coins.Price":{$gt:1000}}
}
])

推荐阅读