gpt4 book ai didi

node.js - 如何在 Mongoose 中排序、选择和查询子文档

转载 作者:可可西里 更新时间:2023-11-01 10:30:37 26 4
gpt4 key购买 nike

因此,我尝试对子文档进行排序,但也尝试对所有内容进行选择。似乎我不能使用常规查询,所以我尝试使用 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 来做到这一点?

最佳答案

您可以更改您的 $project 以 reshape 输出以提供您正在寻找的结构:

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' } ]

关于node.js - 如何在 Mongoose 中排序、选择和查询子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25932690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com