【问题标题】:Aggregation if local field exist in foreign field如果本地字段存在于外部字段中,则进行聚合
【发布时间】:2019-08-01 13:49:55
【问题描述】:

我正在使用 MeteorJS。现在我正在尝试使用流星调用方法获取数据。它运作良好。但是我有$lookup 用于聚合,它也可以正常工作。现在我试图只通过唯一的方式获取数据,不需要重复。

[![Meteor.methods({
        allIndications(someId) {
            const indications = Promise.await(
                Medicines.aggregate(\[
                    {
                        $lookup: {
                            from: "indications",
                            localField: "medicine_indications",
                            foreignField: "_id",
                            as: "AllIndications"
                        }
                    },
                    {
                        $unwind: {
                            path: "$AllIndications",
                            preserveNullAndEmptyArrays: true
                        }
                    },

                    { $project: { _id: 1, AllIndications: 1 } }
                \]).toArray()
            );
            return indications;
        }
    });][1]][1]

【问题讨论】:

  • 在最后一个 AllIndications 上再添加一个阶段 $group。您将获得独特的适应症。

标签: javascript reactjs mongodb meteor aggregation


【解决方案1】:

你可以试试这个

[![Meteor.methods({
    allIndications(someId) {
        const indications = Promise.await(
            Medicines.aggregate(\[
                {
                    $lookup: {
                        from: "indications",
                        localField: "medicine_indications",
                        foreignField: "_id",
                        as: "AllIndications"
                    }
                },
                {
                    $unwind: {
                        path: "$AllIndications",
                        preserveNullAndEmptyArrays: true
                    }
                },
                {
                     $group:{
                         _id:null,
                         AllIndications:{$addToSet: "$AllIndications"}
                     }
                },
                { $project: { _id: 1, AllIndications: 1 } }
            \]).toArray()
        );
        return indications;
    }
});][1]][1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2014-10-19
    • 2022-10-31
    相关资源
    最近更新 更多