首页 文章

Mongodb匹配对象数组

提问于
浏览
-1

我的架构:

const UserSchema = new Schema({
  firstname: { type: String },
  lastname: { type: String }
});

假设我有一个集合 users ,其中包含以下文档:

{ "_id" : 1, "firstname" : "hello", "lastname" : "world" }
{ "_id" : 2, "firstname" : "hello", "lastname" : "earth" }

客户端向我的服务器发送下面的搜索查询 . 使用mongoose,我需要查询mongodb,它应该返回带有与第二个对象匹配的_id 1的用户 .

[{
  firstname: 'hello',
  lastname: 'you'
},
{
  firstname: 'hello',
  lastname: 'world'
}
{
  firstname: 'hello',
  lastname: 'hello'
}]

请注意搜索查询不是静态的,它可以是:

[{
  firstname: 'fsefsefsef',
  lastname: 'fsefsecsfe'
},
{
  firstname: 'fsefsef',
  lastname: 'esfsf'
}
{
  firstname: 'zefzef',
  lastname: 'fzefzfz'
}]

在这种情况下,结果应该是一个空数组,因为没有用户匹配查询中的任何对象

1 回答

  • 0

    您只需在 find 方法中传递该对象即可 .

    User.find(query[1])
    

相关问题