我的架构如下:
var EntitySchema = new Schema({
name : {type: String, default: null},
organizations : [{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Organization'
}}]
});
我有一个组织 ID,如何查询 Entity.find({}) 并找到在其组织数组中具有此 ID 的实体?
我在 mongo shell 中使用了这个
db.entity.find({"organizations.id": { $in: [ObjectId("ididididididid")]}}).pretty()
它有效,但在快速方法中不起作用,我做错了什么吗? $in 可以双向使用吗?我有一种感觉,这不是我应该在这个查询中使用的。
最佳答案
根据mongo文档,可以如下查询
db.entity.find({ "organizations" : { $elemMatch: { "id" : ObjectId("ididididididid") } }}).pretty();
引用: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/
关于node.js - Mongoose 查询检查搜索元素数组中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58933971/