MongoDB聚合Lookup后拼接成员photo字段报错的解决方法
解决MongoDB聚合中数组内字段拼接前缀的问题
嗨,我明白你遇到的问题了——直接在$project里用$concat处理$Members.photo会报错,是因为$Members.photo是一个数组类型(对应返回的所有成员的photo字段集合),而$concat只能接收字符串参数,没法直接处理数组。
要解决这个问题,你需要先遍历Members数组里的每一个成员对象,单独对每个对象的photo字段做拼接操作,这里可以用MongoDB的$map操作符来实现。
下面是修改后的完整聚合查询语句:
db.getCollection('events').aggregate([ { $match: { _id: ObjectId("5e8b0bac041a913bc608d69d")}}, { "$lookup": { "from": "members", "localField": "members.memberId", "foreignField": "_id", "as": "Members" } }, { $project: { "Members": { $map: { input: "$Members", as: "item", in: { "_id": "$$item._id", "firstname": "$$item.firstname", "photo": { $concat: ["http://myurl", "$$item.photo"] } } } } }} ])
关键逻辑说明:
$map会遍历$Members数组中的每一个元素(用as定义别名item)- 对每个
item,我们重新构造对象:保留_id和firstname,同时用$concat把前缀http://myurl和当前item的photo字段拼接起来 - 这样
$concat处理的就是单个字符串,不会再出现数组类型不匹配的错误
执行这个查询后,你会得到每个成员的photo字段都带上了指定前缀的结果,比如:
{ "_id" : ObjectId("5e8b0bac041a913bc608d69d"), "Members" : [ { "_id" : ObjectId("5e7dbf5b257e6b18a62f2da9"), "firstname" : "raed", "photo" : "http://myurl/users/5e7dbf5b257e6b18a62f2da9/profile/profile-02b13aef6e.png" }, { "_id" : ObjectId("5e7e2f048f80b46d786bfd67"), "firstname" : "sarra", "photo" : "http://myurl/5e7e2f048f80b46d786bfd67/profile/profile-c79f91aa2e.png" } ] }
内容的提问来源于stack exchange,提问作者user2285831
相关产品推荐
相关产品推荐

