从 collection 中检索 sub-document,条件为 mongodb

Retrive sub-document from collection with condition in mongodb

贝尔沃是我的collection

"_id" : ObjectId("5b435afff64f913c51799334"),
    "_class" : "com.games24x7.mongo.ChatMessageClanId",
    "chatMessage" : [
        {
            "playerId" : NumberLong(230000034),
            "message" : "Hi ",
            "messageType" : "NORMAL",
            "chatTime" : NumberLong("1530894311114"),
            "chatSequence" : 1
        },
        {
            "playerId" : NumberLong(230000034),
            "message" : "Hi ",
            "messageType" : "NORMAL",
            "chatTime" : NumberLong("1530894311114"),
            "chatSequence" : 2
        },
        {
            "playerId" : NumberLong(230000034),
            "message" : "Hi ",
            "messageType" : "NORMAL",
            "chatTime" : NumberLong("1530894311114"),
            "chatSequence" : 3
        },
        {
            "playerId" : NumberLong(230000034),
            "message" : "Hi ",
            "messageType" : "NORMAL",
            "chatTime" : NumberLong("1530894311114"),
            "chatSequence" : 4
        }],
    "clanId" : 1

我想以如下格式检索数据:

"chatMessage" : [{
                "playerId" : NumberLong(230000034),
                "message" : "Hi ",
                "messageType" : "NORMAL",
                "chatTime" : NumberLong("1530894311114"),
                "chatSequence" : 3
            },
            {
                "playerId" : NumberLong(230000034),
                "message" : "Hi ",
                "messageType" : "NORMAL",
                "chatTime" : NumberLong("1530894311114"),
                "chatSequence" : 4
            }]

我试过以下查询:

db.chatMessageClanId.find({clanId:1,"chatMessage.chatSequence":{$gt:2}}) db.chatMessageClanId.find({clanId:2,"chatMessage.chatSequence":{$gt:2}},{chatMessage:1})

您可以尝试使用 $filter 聚合

db.collection.aggregate([
  { $match: { clanId: 1 }},
  {
    $project: {
      chatMessage: {
        $filter: {
          input: "$chatMessage",
          as: "chatMsg",
          cond: {
            $gt: [
              "$$chatMsg.chatSequence",
              2
            ]
          }
        }
      },
      _class: 1,
      clanId: 1
    }
  }
])

输出

[
  {
    "_class": "com.games24x7.mongo.ChatMessageClanId",
    "_id": ObjectId("5b435afff64f913c51799334"),
    "chatMessage": [
      {
        "chatSequence": 3,
        "chatTime": 1530894311114,
        "message": "Hi ",
        "messageType": "NORMAL",
        "playerId": 230000034
      },
      {
        "chatSequence": 4,
        "chatTime": 1530894311114,
        "message": "Hi ",
        "messageType": "NORMAL",
        "playerId": 230000034
      }
    ],
    "clanId": 1
  }
]

试一试here