在 MongoDB 中提取指定字段值
要获取特定字段值,请使用 $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" }
广告