按给定字段搜索嵌套对象的数组

按给定字段搜索嵌套对象的数组,第1张

按给定字段搜索嵌套对象数组

您可以尝试下面的mongo shell聚合管道。

$match
在某些房间属性(例如
_id
)上。

$unwind
消息(将
messages
数组转换为object)在房间里。

$match
在输入正则表达式上针对
text
要过滤的字段
messages

$group
将消息对象放回到
messages
数组中。

$project
排除
_id
并仅包括
messages
用于输出。

db.collection.aggregate({$match:{"_id":roomid}}, {$unwind:"$messages"}, {$match:{"messages.text": { $regex: /textToFind/i } }},{$group:{_id:null,messages:{$push:"$messages"}}}, {$project:{_id:0, messages:1}})

以下是未经测试的mgo当量。

match1 := bson.M{    "$match": bson.M{        "_id": roomid,    },}unwind := bson.M{    "$unwind": "$messages",}match2 := bson.M{    "$match": bson.M{"messages.text": &bson.RegEx{Pattern: textToFind, Options: "i"}},}group := bson.M{    "$group": bson.M{        "_id": null,        "messages": bson.M{ "$push": "$messages",        },    },}project := bson.M{    "$project":  bson.M{        "_id": 0,         "messages":1,    },}all := []bson.M{match1, unwind, match2, group, project}pipe := collection.Pipe(all)result := []bson.M{}err := pipe.All(&result)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4903945.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存