MongoDB查询以获取范围之间的元素(不包括用于设置范围的两个数字)?
假设两个数字分别为50和60。您可以使用以下语法-
db.yourCollectionName.find({yourFieldName: { $gt : 50 , $lt : 60 } } );
如果您想同时包含50和60,请使用以下语法-
db.yourCollectionName.find({yourFieldName: { $gte : 50 , $lte : 60 } } );
首先让我们创建一个包含文档的集合-
> db.returnEverythingBetween50And60.insertOne({"Amount":55}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c42eedc6604c74817cdb") } > db.returnEverythingBetween50And60.insertOne({"Amount":45}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c432edc6604c74817cdc") } > db.returnEverythingBetween50And60.insertOne({"Amount":50}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c436edc6604c74817cdd") } > db.returnEverythingBetween50And60.insertOne({"Amount":59}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c43aedc6604c74817cde") } > db.returnEverythingBetween50And60.insertOne({"Amount":60}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c43eedc6604c74817cdf") } > db.returnEverythingBetween50And60.insertOne({"Amount":49}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c442edc6604c74817ce0") } > db.returnEverythingBetween50And60.insertOne({"Amount":71}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c445edc6604c74817ce1") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.returnEverythingBetween50And60.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd3c42eedc6604c74817cdb"), "Amount" : 55 } { "_id" : ObjectId("5cd3c432edc6604c74817cdc"), "Amount" : 45 } { "_id" : ObjectId("5cd3c436edc6604c74817cdd"), "Amount" : 50 } { "_id" : ObjectId("5cd3c43aedc6604c74817cde"), "Amount" : 59 } { "_id" : ObjectId("5cd3c43eedc6604c74817cdf"), "Amount" : 60 } { "_id" : ObjectId("5cd3c442edc6604c74817ce0"), "Amount" : 49 } { "_id" : ObjectId("5cd3c445edc6604c74817ce1"), "Amount" : 71 }
以下是查询以返回介于50和60之间的所有内容(不包括这两个数字)-
> db.returnEverythingBetween50And60.find({Amount: { $gt : 50 , $lt : 60 } } );
这将产生以下输出-
{ "_id" : ObjectId("5cd3c42eedc6604c74817cdb"), "Amount" : 55 } { "_id" : ObjectId("5cd3c43aedc6604c74817cde"), "Amount" : 59 }