與欄位不包含陣列中值的 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" ] }
廣告