MongoDB将字段和切片投影限制在一起?
使用$slice运算符。首先让我们创建一个包含文档的集合-
> db.limitAndSliceProjectionDemo.insertOne( { "_id" : 101, "UserName" : "Carol", "UserAge" : 26, "UserMesssage" : [ "Hi", "Hello", "Bye", "Awesome", "Good", "Bad", "Nice", "Good Night", "Good Morning" ] } ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.limitAndSliceProjectionDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "UserName" : "Carol", "UserAge" : 26, "UserMesssage" : [ "Hi", "Hello", "Bye", "Awesome", "Good", "Bad", "Nice", "Good Night", "Good Morning" ] }
以下是限制字段并一起执行切片投影的查询。在这里,我们从2切成4-
> db.limitAndSliceProjectionDemo.find({ "UserName" : "Carol" }, {"_id": 0, "UserName":0,"UserAge":0, "UserMesssage": { "$slice": [2,4] } }).pretty();
这将产生以下输出-
{ "UserMesssage" : [ "Bye", "Awesome", "Good", "Bad" ] }