简体   繁体   English

仅返回Mongodb集合中数组字段的一部分

[英]Returning only part of an array field in a Mongodb collection

I have a very simple test collection in a Mongodb database. 我在Mongodb数据库中有一个非常简单的测试集合。 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". 例如,我想做的只是返回数组“数据”的2个元素。 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. $match首先过滤掉一些不需要的文档。
  2. $unwind array to object. $unwind数组到对象。
  3. $match again to check condition on array elements which are no converted as a sperate object. $match再次检查未转换为独立对象的数组元素的条件。
  4. $group again creating a same single document but we will now push those filtered array element and make it again as an array. $group再次创建相同的单个文档,但是我们现在将这些过滤的数组元素压入并再次使其作为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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