简体   繁体   中英

Returning only part of an array field in a Mongodb collection

I have a very simple test collection in a Mongodb database. One item in that collection looks like the following:

_id: ObjectId()
name: test
data: an array of 6 elements

What I would like to do, for example, is return just 2 elements of the array "data". How do I do this?

I found a similar question on here but couldn't get the answer to work.

Sample data:

{
  "_id" : ObjectId("5bd9f112f255307d51f3257a"),
  "name" : "foo",
  "data" : [ 1, 2, 4, 5, 6 ]
}

Aggregation: Check here

db.getCollection('tests').aggregate([
  {$match: {name: "foo"}},
  {$unwind: "$data"},
  {$match: {data: {$gt: 4}}},
  {$group: {
    _id: "$_id",
    name: {$first: "$name"},
    data: {$push: "$data"}
  }}
]);

Output:

{
  "_id" : ObjectId("5bd9f112f255307d51f3257a"),
  "name" : "foo",
  "data" : [ 5, 6 ]
}

Steps:

  1. $match to filter some unwanted document first.
  2. $unwind array to object.
  3. $match again to check condition on array elements which are no converted as a sperate object.
  4. $group again creating a same single document but we will now push those filtered array element and make it again as an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM