要获取特定的字段值,请使用$in运算符。$in选择文档,其中字段的值等于指定数组中的任何值。
首先让我们创建一个包含文档的集合-
> db.indexesDemo.createIndex({"StudentFirstName":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de4d25ddae1f53b621dd") } > db.indexesDemo.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de5825ddae1f53b621de") } > db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de6725ddae1f53b621df") } > db.indexesDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de7225ddae1f53b621e0") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.indexesDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5e06de4d25ddae1f53b621dd"), "StudentFirstName" : "John", "StudentLastName" : "Smith" } { "_id" : ObjectId("5e06de5825ddae1f53b621de"), "StudentFirstName" : "Chris", "StudentLastName" : "Brown" } { "_id" : ObjectId("5e06de6725ddae1f53b621df"), "StudentFirstName" : "John", "StudentLastName" : "Doe" } { "_id" : ObjectId("5e06de7225ddae1f53b621e0"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
以下是对索引的查询-
> db.indexesDemo.find( ... { StudentFirstName: { $in: [ "John", "David" ] } }, ... { _id: 0, StudentLastName: 0 } ... );
这将产生以下输出-
{ "StudentFirstName" : "David" } { "StudentFirstName" : "John" } { "StudentFirstName" : "John" }