MongoDB查询仅过滤内容中包含“工作”一词的日志
要过滤包含单词“work”的日志,请aggregate()
与$filter一起使用。首先让我们创建一个包含文档的集合-
> db.demo383.insertOne( ... { ... "ServerName":"Jboss", ... "ServerLogs": [ ... { ... "status":"Working" ... }, ... { ... "status":"Stop" ... }, ... { ... "status":"Worked" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5b635422064be7ab44e7f1") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo383.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e5b635422064be7ab44e7f1"), "ServerName" : "Jboss", "ServerLogs" : [ { "status" : "Working" }, { "status" : "Stop" }, { "status" : "Worked" } ] }
以下是要过滤的查询-
> db.demo383.aggregate([ ... { "$addFields": { ... "ServerLogs": { ... "$filter": { ... "input": "$ServerLogs", ... "cond": { ... "$ne": [ ... { "$indexOfBytes": [ ... { "$toUpper": "$$this.status" }, ... { "$toUpper": "work" } ... ]}, ... -1 ... ] ... } ... } ... } ... }} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e5b635422064be7ab44e7f1"), "ServerName" : "Jboss", "ServerLogs" : [ { "status" : "Working" }, { "status" : "Worked" } ] }