Mongodb:是否可以使用$ ne从项目数组中返回其他值?

时间:2019-06-27 08:24:27

标签: mongodb

mongo $ne是否可以在$project中返回值而不是truefalse

文档:

{
    "_id" : ObjectId("5d1449db6f934a2926c175d1"),
    "clients" : [ 
        "82", 
        "85"
    ],
    "roomId" : 1,
    "message" : [ 
        {
            "time" : ISODate("2019-06-27T04:44:49.528Z"),
            "status" : "SEND",
            "text" : "Ellorad",
            "sender" : "82",
            "reciever" : "82",
            "_id" : ObjectId("5d1449db6f934a2926c175d2")
        }, 
        {
            "time" : ISODate("2019-06-27T04:44:49.528Z"),
            "status" : "SEND",
            "text" : "helas veronaaah",
            "sender" : "82",
            "reciever" : "85",
            "_id" : ObjectId("5d1449ff6f934a2926c175d3")
        }
    ]
}

我尝试过的:

    Chat.aggregate([
      { $match: { clients: 82 } },
      {
        $project: {
          _id: '$roomId',
          receiver: { $ne: ['$clients', 82] },
          message: { $slice: ['$message', -1] }
        }
      }
    ])

结果:

{
  "message": [
    {
      "_id": 1,
      "receiver": true
      "message": [
        {
          "time": "2019-06-27T04:44:49.528Z",
          "status": "SEND",
          "text": "helas veronaaah",
          "sender": "82",
          "reciever": "85",
          "_id": "5d1449ff6f934a2926c175d3"
        }
      ]
    }
  ]
}

因此接收方在这里只是返回true或false,考虑到其$ne是正确的,但是我想要的结果是,此处的接收方为'85'而不是true或{{1 }}

1 个答案:

答案 0 :(得分:0)

为什么不呢?

1)unwind客户数组,和

2)在下一阶段使用$match排除不需要的值(在这种情况下为82)

3)使用$project阶段获得所需的结果,clients将具有所需的receiver

尝试一下:

Chat.aggregate([
  { $match: { clients: 82 } },
  {
      $unwind : "clients"
  },
  {
      $match : {
          clients : {$ne : 82}
      }
  },
  {
      $project : {
            _id: '$roomId',
            receiver: "$clients",
            message: { $slice: ['$message', -1] }
      }
  }
])
相关问题