简体   繁体   English

MongoDB:按数组中的一个objectId查找

[英]MongoDB: find by one objectId in array

I'm having trouble with query the DB, I want to get all element that the have for example: admin "54bd13864ec56c7c12310a79" in the admins array, 我在查询数据库时遇到麻烦,我想获取所有具有的元素,例如:admins数组中的admin“ 54bd13864ec56c7c12310a79”,

tried it with "$in" but it didn't worked, could it be related to the fact that its an ObjectId? 用“ $ in”尝试过它,但是没有用,这可能与它的ObjectId有关吗?

trainerId = '54bd13864ec56c7c12310a79'
GroupSchema.find({'admins': { $in: [ trainerId ] }}

This is my db: 这是我的数据库:

{
   "_id" : ObjectId("54b93e8e3801ae381e3433be"),
   "groupName" : "Developers Groups",
   "createdBy" : "Ido",
   "creationDate" : "Jan 16 2015",
   "users" : [ 
       ObjectId("54b932c7ac3ec34a85e6246c")
   ],
   "admins" : [ 
       ObjectId("54b932c7ac3ec34a85e6246c"), 
       ObjectId("54bd13864ec56c7c12310a79")
   ],
   "__v" : 0
}

The Schema model is: 模式模型是:

module.exports = mongoose.model('Groups' ,
{
    groupName: String,
    createdBy: String,
    creationDate: String,
    admins: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Users' }],
    users: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Users' }]
}
);

This is ObjectId: 这是ObjectId:

ObjectId("54bd13864ec56c7c12310a79") ObjectId(“ 54bd13864ec56c7c12310a79”)

and this is string: 这是字符串:

trainerId = '54bd13864ec56c7c12310a79' trainerId ='54bd13864ec56c7c12310a79'

So maybe you should use ObjectId in your query. 因此,也许您应该在查询中使用ObjectId。

Convert the id string to ObjectId: 将id字符串转换为ObjectId:

var mongoose = require('mongoose'),
    trainerId = '54bd13864ec56c7c12310a79';
var id = mongoose.Types.ObjectId(trainerId);

GroupSchema.find({'admins': id });

If I understand your question correctly, you probably want to use $elemMatch for this. 如果我正确理解了您的问题,则可能要为此使用$ elemMatch $in should be used when you want to check if a non-array field is equals one of the values specified in the array you pass to $in. 当您要检查非数组字段是否等于传递给$ in的数组中指定的值之一时,应使用$ in。

如果我正确理解您的问题,则可以尝试将$unwind汇总,在管理员中将元素分开。

It looks like you want to match the parent document with a subdocument id. 看起来您想将父文档与子文档ID匹配。 You can either use a simple query: 您可以使用一个简单的查询:

GroupSchema.find({'admins._id': trainerId}})

Or you could use $elemMatch , but as the doc says it's not necessary: If you specify only a single condition in the $elemMatch expression, you do not need to use $elemMatch. 或者,您可以使用$ elemMatch ,但正如文档所述,这是没有必要的: 如果在$ elemMatch表达式中仅指定一个条件,则无需使用$ elemMatch。

GroupSchema.find({admins: {$elemMatch: {_id: trainerId}}})

As far as casting the string value to an ObjectId , mongoose will automatically do this for you internally. 至于将字符串值转换为ObjectId ,猫鼬会在内部自动为您执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM