我正在做一个项目,我有如下的数据。我想使用MongoDB聚合。这里有些对象有like值,有些没有。现在我想使用like的值,如果它可用的话,否则我想取dislikes的值。如果没有like或dislikes可用的话,我不想取这个。
const data = [
{ _id :0, name:"jane", joined : ISODate("2011-03-02"), dislikes: 9},
{ _id :1, name: "joe", joined : ISODate("2012-07-02")},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), likes: 60, dislikes: 02},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), dislikes: 12},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), dislikes: 12},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), }
],
输出将如下所示:
[
{ _id :0, name:"jane", joined : ISODate("2011-03-02"), dislikes: 9},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), likes: 60, dislikes: 02},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), dislikes: 12},
{ _id: 2, name: "Ant", joined: ISODate("2012-07-02"), dislikes: 12},
],
有什么方法可以让我做汇总吗?谢谢。
1条答案
按热度按时间rt4zxlrg1#
只需将2个
$exists
条件 Package 在一个$or
中。Mongo Playground