要动态构建查询,您需要编写一些脚本。首先让我们创建一个包含文档的集合-
> 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" ] }