如何动态构建 MongoDB 查询?
要动态构建查询,需要编写一些脚本。让我们首先使用文档创建一个集合 -
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef5c5def71edecf6a1f69a") } > db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef5c73ef71edecf6a1f69b") } > db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef5c8bef71edecf6a1f69c") }
使用 find() 方法显示集合中的所有文档 -
> db.dynamicQueryDemo.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5cef5c5def71edecf6a1f69a"), "Name" : "John", "Subject" : [ "MongoDB", "MySQL" ] } { "_id" : ObjectId("5cef5c73ef71edecf6a1f69b"), "Name" : "John", "Subject" : [ "C", "C++" ] } { "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"), "Name" : "John", "Subject" : [ "MongoDB", "Java" ] }
以下是动态构建 MongoDB 查询的查询 -
> function findDocument(subject) { var find = {}; if (subject.length == 0) find["$nin"] = subject; else find["$in"] = subject; return find; } > var sub = ["MySQL","MongoDB"]; > var myDoc = findDocument(sub); > db.dynamicQueryDemo.aggregate([{ $match: { "Subject": myDoc, } }]);
这将产生以下输出 -
{ "_id" : ObjectId("5cef5c5def71edecf6a1f69a"), "Name" : "John", "Subject" : [ "MongoDB", "MySQL" ] } { "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"), "Name" : "John", "Subject" : [ "MongoDB", "Java" ] }
广告