与字段不包含数组中值的 MongoDB 文档匹配?
要匹配字段不包含数组中值的文档,请使用 $nin。我们创建一个包含文档的集合 -
> db.demo180.insertOne({"Scores":["80","90","110"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3988a69e4f06af551997fb") } > db.demo180.insertOne({"Scores":["110","70","60"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3988b79e4f06af551997fc") } > db.demo180.insertOne({"Scores":["40","70","1010"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3988cc9e4f06af551997fd") }
使用 find() 方法显示集合中的所有文档 -
> db.demo180.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e3988a69e4f06af551997fb"), "Scores" : [ "80", "90", "110" ] } { "_id" : ObjectId("5e3988b79e4f06af551997fc"), "Scores" : [ "110", "70", "60" ] } { "_id" : ObjectId("5e3988cc9e4f06af551997fd"), "Scores" : [ "40", "70", "1010" ] }
以下是匹配字段不包含数组中值的文档的查询 -
> db.demo180.aggregate({ "$match": { "Scores": { "$nin": ["110","90"] } } }).pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5e3988cc9e4f06af551997fd"), "Scores" : [ "40", "70", "1010" ] }
广告