A simple projection
A little use of mongodb know that the projection is very simple, directly
db.student.find({_id:ObjectId(‘5a5085aed8f10c1a6cc0395b‘)},{comments: 1})
Add a $slice projection
However, when I want to give comments ( $slice
) How to do it?
The wrong approach
The following are the wrong practices
db.student.find({_id:ObjectId(‘5a5085aed8f10c1a6cc0395b‘)},{comments: 1, comments:{$slice:[0,1]}})
In this case, only the pagination, and then the fields Show All .
reason :
Object, the same name field, which overrides the former. So the only thing that {comments: 1, comments: {$slice:[0,1]}}
actually comes into effect is comments:{$slice:[0,1]}
.
Similarly, if the two swap positions become {comments: {$slice:[0,1]}, comments: 1}
, then the actual effect is comments: 1
that there is no paging .
The correct wording
$elemMatch
, can do
db.student.find({_id:ObjectId(‘5a5085aed8f10c1a6cc0395b‘)}, {comments:{$slice:[0,1]}, $elemMatch:1})
For $elemMatch
, this usage is not described in the official website documentation. So I don't know if this is astray , haha.
There are other more elegant wording to tell
How to use the spring
In spring, query is assembled as follows. Use the normal include to write.
Query query = new Query();query.addCriteria(Criteria.where("_id").is(new ObjectId("5a5085aed8f10c1a6cc0395b")));query.fields().slice("comments", 0, 1);query.fields().include("$elemMatch");
The wrong way of spelling
query.fields().slice("comments", 0, 1).elemMatch("comments", new Criteria());
So the spell will turn out
db.student.find({_id:ObjectId(‘5a5085aed8f10c1a6cc0395b‘)}, {comments:{$slice:[0,1]}, $elemMatch: {}})
And this statement will be an error if directly executed in MongoDB.
MongoDB projection has $slice how to display only this field