代码之家  ›  专栏  ›  技术社区  ›  mandaputtra

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

  •  0
  • mandaputtra  · 技术社区  · 7 年前

    can蒙古人 $ne 返回值 $project 而不是 true 或 false 是吗?

    文件:

    {
        "_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"
            }
          ]
        }
      ]
    }
    

    所以接收者只是在这里返回对或错,这是对的,考虑到它 新台币 但是我想要的结果是,这里的接收者是“85”,而不是 对 或 错误

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ravi Shankar Bharti    7 年前

    unwind

    $match

    $project clients receiver

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