查找符合条件的所有子文档

时间:2017-07-05 21:48:10

标签: mongodb mongoose mongodb-query aggregation-framework

我想只从我的两个对象数组file_historyuploaded_files中获得符合criteira的子文档。即使我发现这个stackoverflow回答#2(Mongoose - finding subdocuments by criteria)它对我来说不起作用,或者我错过了什么。

var projectId = req.params.projectId
var uploadId = req.body.uploadId

let populateQuery = [
    {path: 'owner'},
    {path: 'uploaded_files.file', match: {upload_id: uploadId}},
    {path: 'file_history.file', match: {upload_id: uploadId}}
]

Project.findOne({ project_id: projectId }).populate(populateQuery).then(project => {
    console.log(project)
})

我的文档如下所示:

{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-05T21:45:46.754Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [ 
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        }, 
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : ISODate("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [ 
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-04T21:58:22.000Z")
        }, 
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : ISODate("2017-07-05T02:17:51.000Z")
        }
    ]
}

它将打印项目及其file_historyuploaded_files中的所有子文档。但是我只想获得与给定的upload_id匹配的子文档。我做错了什么?

编辑:此问题是指使用mongoose解决问题。我无法在Mongoose中使用此问题的聚合语句(Retrieve only the queried element in an object array in MongoDB collection),因为它返回了一个空数组,但是我能够通过MongoDB运行它,它确实返回了所需的结果。那是我试过的代码:

    let projectId = req.params.projectId // Project ID is an integer and no objectId
    let uploadId = new mongoose.Types.ObjectId(req.body.uploadId)
    console.log(`ProjectID: ${projectId}, uploadId: ${uploadId}, params: ${req.body.uploadId}`)

    let populateQuery = [
        {path: 'owner'},
        {path: 'uploaded_files.file'},
        {path: 'file_history.file'}
    ]

    Project.aggregate(
        {$match: {"project_id": projectId}},
        {$project: {
            uploaded_files: {$filter: {
                    input: '$uploaded_files',
                    as: 'uploadedFile',
                    cond: {$eq: ['$$uploadedFile.upload_id', uploadId]}
                }}
            }
        }
    ).then(project => {
        console.log(project)
})

console.log返回:ProjectID: 13, uploadId: 595c0f7ea1d20247285be5f5, params: 595c0f7ea1d20247285be5f5这是正确的(存在ID)

1 个答案:

答案 0 :(得分:1)

你正在做一些可怕的错误而且不清楚那是什么。因此,向您展示的最佳方式是示例。

另请注意,单个匹配"甚至不需要$filter。而standard positional projection只会在这里做:

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      ObjectId = require('mongodb').ObjectID

mongoose.set('debug',true)
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/test');

const doc =
{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : new Date("2017-07-05T21:45:46.754Z"),
    "created_at" : new Date("2017-06-05T18:34:07.150Z"),
    "owner" : ObjectId("591eea4439e1ce33b47e73c3"),
    "name" : "RDemo project",
    "uploaded_files" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "account working.txt",
            "file" : ObjectId("595c0f7ea1d20247285be5f4"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-04T21:58:22.000Z")
        },
        {
            "display_name" : "Log_28-6-2017_14-17-53-562.txt",
            "file" : ObjectId("595c4c4f3ae2470700ea07e2"),
            "upload_id" : ObjectId("595c0f7ea1d20247285be5f5"),
            "created_at" : new Date("2017-07-05T02:17:51.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        },
        {
            "display_name" : "Coon.png",
            "file" : ObjectId("595c4c553ae2470700ea07e4"),
            "upload_id" : ObjectId("595c4c553ae2470700ea07e5"),
            "created_at" : new Date("2017-07-05T02:17:57.000Z")
        }
    ]
};

const Test = mongoose.model('Test', new Schema({}, { strict: false }) );

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert data
    (callback) => Test.insertMany(doc,callback),

    // Correct usage of $filter
    (callback) =>
      Test.aggregate(
        [
          { "$match": { "project_id": 13 } },
          { "$addFields": {
            "uploaded_files": {
              "$filter": {
                "input": "$uploaded_files",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            },
            "file_history": {
              "$filter": {
                "input": "$file_history",
                "as": "f",
                "cond": {
                  "$eq": [
                    "$$f.upload_id", ObjectId("595c0f7ea1d20247285be5f5")
                  ]
                }
              }
            }

          }}
        ],
        (err,results) => {
          if (err) callback(err);
          log(results);
          callback();
        }
      ),

      // Just a normal positional project for 1 match
      (callback) => Test.findOne(
        { "uploaded_files.upload_id": ObjectId("595c0f7ea1d20247285be5f5") },
        { "uploaded_files.$": 1 },
        (err,result) => {
          if (err) callback(err);
          log(result);
          callback();
        }
      )

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)

产生所需的输出:

[
  {
    "_id": "5935a41f12f3fac949a5f925",
    "__v": 0,
    "project_id": 13,
    "updated_at": "2017-07-05T21:45:46.754Z",
    "created_at": "2017-06-05T18:34:07.150Z",
    "owner": "591eea4439e1ce33b47e73c3",
    "name": "RDemo project",
    "uploaded_files": [
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ],
    "file_history": [
      {
        "created_at": "2017-07-04T21:58:22.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c0f7ea1d20247285be5f4",
        "display_name": "account working.txt"
      },
      {
        "created_at": "2017-07-05T02:17:51.000Z",
        "upload_id": "595c0f7ea1d20247285be5f5",
        "file": "595c4c4f3ae2470700ea07e2",
        "display_name": "Log_28-6-2017_14-17-53-562.txt"
      }
    ]
  }
]
Mongoose: tests.findOne({ 'uploaded_files.upload_id': ObjectId("595c0f7ea1d20247285be5f5") }, { fields: { 'uploaded_files.$': 1 } })
{
  "_id": "5935a41f12f3fac949a5f925",
  "uploaded_files": [
    {
      "display_name": "Log_28-6-2017_14-17-53-562.txt",
      "file": "595c4c4f3ae2470700ea07e2",
      "upload_id": "595c0f7ea1d20247285be5f5",
      "created_at": "2017-07-05T02:17:51.000Z"
    }
  ]
}