【问题标题】:How to sort, select and query subdocument in mongoose如何在猫鼬中排序、选择和查询子文档
【发布时间】:2014-11-13 23:25:27
【问题描述】:

所以我正在尝试对子文档进行排序,但也要选择和一切。似乎我不能使用常规查询,所以我尝试使用 aggregate

mongoose = require("mongoose");
mongoose.connect("localhost:27017", function(err) {
  mongoose.connection.db.dropDatabase();
  Story = mongoose.model("Story", {
    title: String,
    comments: [{
      author: String,
      content: String
    }]
  });
  sample = new Story({
    title: "Foobar",
    comments: [
    {
      author: "A author",
      content: "1 Content"
    },
    {
      author: "B author",
      content: "2 Content"
    }
    ]
  });
  sample.save(function(err, doc) {
    Story.aggregate([
        { $match: {
            _id: doc._id
        }},
        { $unwind: "$comments" },
        { $project: {"comments": 1}},
        { $sort: {"comments.author": -1}}
    ], function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(result);
    });
  })
});

这几乎可以工作:

[ { _id: 541c0f8098f85ac41c240de4,
    comments:
     { author: 'B author',
       content: '2 Content',
       _id: 541c0f8098f85ac41c240de5 } },
  { _id: 541c0f8098f85ac41c240de4,
    comments:
     { author: 'A author',
       content: '1 Content',
       _id: 541c0f8098f85ac41c240de6 } } ]

但我想要什么:

[ { author: 'B author',
   content: '2 Content',
   _id: 541c0f8098f85ac41c240de5 },
 { author: 'A author',
   content: '1 Content',
   _id: 541c0f8098f85ac41c240de6 } ]

我可以使用 lodash 的 pluck,但有没有办法只使用 mongodb?

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以更改您的 $project 以重新调整输出以提供您正在寻找的结构:

    Story.aggregate([
        { $unwind: "$comments" },
        { $project: {
            author: '$comments.author',
            content: '$comments.content',
            _id: '$comments._id'
        }},
        { $sort: {author: -1}}
    ], function (err, result) { ...
    

    输出:

    [ { _id: 541c2776149002af52ed3c4a,
        author: 'B author',
        content: '2 Content' },
      { _id: 541c2776149002af52ed3c4b,
        author: 'A author',
        content: '1 Content' } ]
    

    【讨论】:

    • 非常感谢!有没有办法自动做到这一点?没有指定字段?
    • @Vinz243 不,您需要单独命名投影中的每个字段,因为您希望它们位于顶层。
    猜你喜欢
    • 2015-10-01
    • 2015-06-26
    • 2016-08-17
    • 2020-12-02
    • 2017-06-01
    • 1970-01-01
    • 2019-10-19
    • 2014-03-21
    • 1970-01-01
    相关资源
    最近更新 更多