栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以尝试下面的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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号