mongodb 如果某个值在一个集合中可用,则我希望获取一个数据,否则我希望在聚合中获取另一个值

mgdq6dx1  于 2023-01-20  发布在  Go
关注(0)|答案(1)|浏览(116)

我正在做一个项目,我有如下的数据。我想使用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},
],

有什么方法可以让我做汇总吗?谢谢。

rt4zxlrg

rt4zxlrg1#

只需将2个$exists条件 Package 在一个$or中。

db.collection.find({
  $or: [
    {
      likes: {
        $exists: true
      }
    },
    {
      dislikes: {
        $exists: true
      }
    }
  ]
})

Mongo Playground

相关问题