Mongodb: querying array elements in a document

I have a collection that I would like to request as follows:

  • return all documents
  • up to 2 comments (e.g. snippet, 0, 1 or 2 comments)
  • All comments must have submissions> 10

It seems that I need to create a function to evaluate each document separately, but it is not clear how this is done, especially considering that I want to cut and return up to n elements that meet these criteria.

Example circuit:

{ title: "One", comments: [ { title: "comment1", views: 9 }, { title: "comment2", views: 10 }, { title: "comment3", views: 11 }, { title: "comment4", views: 12 }, ] } 

I want to do something like:

 db.collection.find({"comments.views": {$gt: 10}}, {comments:{$slice: 2}}) 

But this returns any document with a comment s> 10 views, and then slices 2 comments ... I want to return those comments that have> 10 elements. I can not do this on the client And use $ slice without losing some comments, so I need to do this on the DB. Thoughts?

+1
mongodb
source share
2 answers

But this returns any document with a comment s> 10 views, and then slices 2 comments

This is the filtering behavior of a multi-level embedded document, usually the corresponding filter returns the entire document, not subsets.

Typically, the positioning operator $ is used to map supporting documents in updates. But the function is not yet implemented in return specifiers.

There is some problem. Mongo support for positional ($) operator in fields returning specification . (Please login to vote if you really need this feature)

So you need to process

  • up to 2 comments (e.g. snippet, 0, 1 or 2 comments)

in your application through a cycle through all collections.

+1
source share

you can take a look at aggregation. First you need to disable it first and then apply the filter:

 db.<your collection>.aggregate( [ { $unwind : "$comments" }, {$match:{"comments.views": {$gt: 10}}} ] ) 

Check the results and apply other actions on this

0
source share

All Articles