在MongoDB聚合中的子集内应用条件?
要应用条件,请使用$setIsSubset。首先让我们创建一个包含文档的集合-
> db.subsetDemo.insertOne({"StudentName":"Chris","StudentFavouriteSubject":["Java","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e063e49150ee0e76c06a052") } > db.subsetDemo.insertOne({"StudentName":"Chris","StudentFavouriteSubject":["Java","Python","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e063e4f150ee0e76c06a053") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.subsetDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e063e49150ee0e76c06a052"), "StudentName" : "Chris", "StudentFavouriteSubject" : [ "Java", "Python" ] } { "_id" : ObjectId("5e063e4f150ee0e76c06a053"), "StudentName" : "Chris", "StudentFavouriteSubject" : [ "Java", "Python", "MySQL" ] }
这是在MongoDB聚合子集中应用条件的查询-
> db.subsetDemo.aggregate([ ... { ... $project: { ... _id: 0, ... StudentName: 1, ... isMySQL: { ... $setIsSubset: [["MySQL"], "$StudentFavouriteSubject"] ... } ... } ... } ... ]);
这将产生以下输出-
{ "StudentName" : "Chris", "isMySQL" : false } { "StudentName" : "Chris", "isMySQL" : true }