如何仅投影MongoDB阵列中的字段?
有一个文档架构,该模式具有一个名为“ updatedFields”
的数组字段,其中包含一些您会在“ OldDocument”
和 “ newDocument”
对象。这是它的图片。
现在我只想投射“ updatedFields”中存在的那些字段
来自“ newDocument”
and 和“ olddocument” 如下:
$project : {
"oldDocument.Modified":1,
"oldDocument.Status":1,
"newDocument.Modified":1,
"newDocument.Status":1
}
有人知道如何在数组中的字段名称上构建项目子句基础吗?我需要mongoDB查询,而不是JS代码。
there is a document schema that has an array field called "updatedFields"
which contains some fields names that you will find in "oldDocument"
and"newDocument"
objects. Here is its picture.
Now I want to project only those fields which exist in "updatedFields"
array from "newDocument"
and "oldDocument"
like below:
$project : {
"oldDocument.Modified":1,
"oldDocument.Status":1,
"newDocument.Modified":1,
"newDocument.Status":1
}
Does anyone know how to build the project clause base on the fields' names in the array? I need a MongoDB query, not js code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
$ objectToArray
为了将键格式化为值,$ filter
根据UPDATEDFIELDS
array,然后使用$ $ ArrayToObject
将它们再次制成键。编辑:根据评论的请求,使用
$ MAP
在过滤器内部使用将日期投入到字符串。像这样的事情:
如您在 Playground )
You can use
$objectToArray
in order to format the keys as values,$filter
them according to theupdatedFields
array and then use$arrayToObject
to make them keys again.Edit: using
$map
inside the filter to cast dates to strings, according to a request on the comments.Something like this:
As you can see on the playground