如果本地字段存在于外部字段中,则进行汇总

时间:2019-03-11 09:22:11

标签: javascript reactjs mongodb meteor aggregation

我正在使用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]

enter image description here

1 个答案:

答案 0 :(得分: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]