MongoDB:如何查找聊天室中有电话号码的消息?

问题描述 投票:1回答:1

我有这个json作为我的留言文件:

{"_id":"nOneDzCuhE",
 "type":"text",
 "_p_chatRoomId":"chatrooms$BSxYYyUX49",
 "chatRoomIdText":"BSxYYyUX49",
 "_p_senderId":"_User$LD0r3WkuUD"
 "message":"Hello World!"
 "senderIdText":"LD0r3WkuUD"
 "_created_at":"2018-08-29 19:52:46.678",
 "_updated_at":"2018-08-29 19:52:46.678"
}

这是我的聊天室文件:

{   "_id":"mfBRNbQ0gd",
    "type":"Individuals",
    "users": [
        0: {"phone_number":"987654321","id":"7AifRl9D3T","name":"user1"},
        1: {"phone_number":"123456789","id":"qapXotisT1","name":"User2"}
    ],
    "_created_at": "2018-08-14 18:11:06.090",
    "_updated_at":"2018-08-14 18:11:06.090"
}

所以,首先我想从chatRoomIdText获取id并使用它来检查这个聊天室是否有我的电话号码(在用户数组下)。

简而言之,我想显示他们的聊天室有我的电话号码的所有消息:例如 - 987654321。

提前致谢。

python mongodb nosql aggregation-framework
1个回答
1
投票

您可以使用$lookup管道变体在3.6中的联接集合中应用$match

假设加入chatRoomIdText_id就像应该适合你。

db.message.aggregate([      
   {"$lookup":{
      "from":"chatroom",
      "let":{"chatRoomIdText":"$chatRoomIdText"},
      "pipeline":[
        {"$match":{
          "$expr":{
           "$and":[
              {"$eq":["$$chatRoomIdText","$_id"]},
              {"$in":["987654321","$users.phone_number"]}
             ]
           }
        }}
      ],
      "as":"lookup-results"
    }},
    {"$match":{"lookup-results.0":{"$exists":true}}},
    {"$project":{"lookup-results":0}}
])
© www.soinside.com 2019 - 2024. All rights reserved.