MongoDB projection has $slice how to display only this field

Source: Internet
Author: User
Tags mongodb projection

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.