belwo是我的收藏
"_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})
答案 0 :(得分: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