gpt4 book ai didi

javascript - 是否可以在具有 $elemMatch 投影的同一集合上使用查询投影?

转载 作者:行者123 更新时间:2023-12-03 12:37:01 25 4
gpt4 key购买 nike

我知道您可以使用 $elemMatch 作为投影来限制子集合数组中的项目。当这样使用它时,它会返回匹配的子文档的所有字段,无论是否也指定了 query projections

是否可以限制匹配子文档中返回的字段?你会怎么做?

使用版本 3.8.9。

给定简单的模式:

var CommentSchema = mongoose.Schema({
body: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}
});

var BlogSchema = mongoose.Schema({
title: String,
blog: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
},
comments: [CommentSchema]
});

var Blog = mongoose.model('Blog',modelSchema);

示例

Blog.findOne({_id: id}, {_id: 1, comments: {$elemMatch: {'created.by': 'Jane'}, body: 1}}, function(err, blog) {
console.log(blog.toJSON());
});
// outputs:
{
_id: 532cb63e25e4ad524ba17102,
comments: [
_id: 53757456d9c99f00009cdb5b,
body: 'My awesome comment',
created: { by: 'Jane', date: Fri Mar 21 2014 20:34:45 GMT-0400 (EDT) }
]
}

// DESIRED OUTPUT
{
_id: 532cb63e25e4ad524ba17102,
comments: [
body: 'My awesome comment'
]
}

最佳答案

是的,有两种方法可以做到这一点。因此您可以使用 $elemMatch在投影方面,与您已经拥有的一样,略有变化:

Model.findById(id,
{ "comments": { "$elemMatch": {"created.by": "Jane" } } },
function(err,doc) {

或者只是添加到查询部分并使用位置 $ 运算符:

Model.findOne(
{ "_id": id, "comments.created.by": "Jane" },
{ "comments.$": 1 },
function(err,doc) {

无论哪种方式都是完全有效的。

如果您想要比这更复杂的东西,您可以使用 .aggregate()方法,它是 $project运算符改为:

Model.aggregate([
// Still match the document
{ "$match": "_id": id, "comments.created.by": "Jane" },

// Unwind the array
{ "$unwind": "$comments" },

// Only match elements, there can be more than 1
{ "$match": "_id": id, "comments.created.by": "Jane" },

// Project only what you want
{ "$project": {
"comments": {
"body": "$comments.body",
"by": "$comments.created.by"
}
}},

// Group back each document with the array if you want to
{ "$group": {
"_id": "$_id",
"comments": { "$push": "$comments" }
}}
],
function(err,result) {

因此,聚合框架的用途远不止于简单地聚合结果。这是$project与使用 .find() 进行投影相比,运算符为您提供了更大的灵 active 。它还允许您过滤并返回多个数组结果,这也是 .find() 中的投影无法完成的事情。

关于javascript - 是否可以在具有 $elemMatch 投影的同一集合上使用查询投影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23691909/

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