mongodb - 如何取消选择数组 MongoDB 中的一个对象?
问题描述
在我的情况下,我只需要我的结果,但我的数组中没有我的 objectID。
这是我的方法:
return Room.findOne(
{
_id: idRoom,
participants: {$elemMatch: {$ne: this.currentUser.profile}},
},
{
'participants.$': 1,
}
)
使用 elementMatch,问题是当您找到对象时,只返回第一个对象。
这是我的结果:
"result": {
"_id": "5da5e77f51e08708b79565e8",
"participants": [
"5da4d5b40cc94f04a7aaad40"
],
这是我需要的真正结果
"result": {
"_id": "5da5e77f51e08708b79565e8",
"participants": [
"5da4d5b40cc94f04a7aaad40"
"fwnert9248yrhnqwid13982r" // I have another participants
],
我的模型是这样的:
const RoomSchema = new Schema({
participants: [{type: Schema.Types.ObjectId,ref: 'Profile'}],
...
}, options)
由于其他原因,我不能使用聚合,如果你有解决方案,谢谢
解决方案
因此,我认为您正在尝试使用该findOne()
方法在 mongo 中塑造结果集,并且聚合管道框架的任何使用都是不可能的,并且由于其他原因不可用。
我不确定这是可能的。我相信您需要执行多个步骤才能达到您想要的结果。如果您可以使用聚合管道框架,这里是一个适合所需结果的管道(我相信)......
db.Room.aggregate(
[
{
"$match": { _id: ObjectId(idRoom)}
},
{
$project: {
"participants": {
$filter: {
input: "$participants",
as: "participant",
cond: {$ne: ["$$participant", this.currentUser.profile] }
}
}
}
}
]
)
...但是如果您不能使用聚合管道,那么这里是一个 mongoshell 脚本,它分几个步骤完成任务。策略是通过 _id 捕获整个文档,然后从数组中删除数据元素,然后回显结果......
var document = db.Room.findOne( { _id: ObjectId("5da64a62cd63abf99d11f210") } );
document.participants.splice(document.participants.indexOf("5da4d5b40cc94f04a7aaad40"), 1);
document;
推荐阅读
- c# - 如何逃离异步任务
- html - CSS - 编辑具有相同宽度的 2 个文本框的响应式表单
- kubernetes - helm cockroachdb GKE - 音量已满且不可调整大小
- arrays - Node js REST Service mongodb distinct 数组为空
- c# - 如果你在顶级类中有 :base() 会发生什么?
- php - 为什么全局变量不需要初始化?
- r - louvain社区检测中检查节点属于哪个社区
- jquery - 使用航点向下滚动到 div 时突出显示导航链接
- c# - 为什么 Task[from metadata] 没有列出公共属性 CompletedTask?
- python - 如何从现有列表创建字典?键值必须是该键的重复次数