如何在 mongoose 中使用一组值查询一组对象? [英] How do I query a set of objects with an array of values in mongoose?

查看:94
本文介绍了如何在 mongoose 中使用一组值查询一组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的架构

const rankSchema = new Schema(
  {
    rank: { type: Object, default: {} },
    lastUpdated: { type: Date, default: Date.now() },
  },
  { minimize: false }
);

我的数据库有一个对象等级",里面有很多其他对象,就像这样.

And my database has an object 'rank' with many other objects inside of it like this.

rank: {
  Person1: { Stat1: 2, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 4 },
  Person2: { Stat1: 4, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 2 },
  Person3: { Stat1: 1, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 1 },
  Person4: { Stat1: 2, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 3 }
}

现在我有一个包含其中一些人的字符串数组

Now I have an array of strings that contains a few of these people

['Person1', 'Person2']

我希望能够找到该数组中的所有人员对象并返回他们的统计信息.所以基本上使用字符串数组后的最终输出将是

I want to be able to find all the person objects in that array and return their stats. So essentially the final output after using the array of strings would be

Person1: { Stat1: 2, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 4 },
Person2: { Stat1: 4, Stat2: 0, Stat3: 0, Stat4: 2, Stat5: 2 }

我尝试使用 $in 和各种不同的查询,但似乎没有任何效果,我很困惑.

I tried using $in and various different queries but nothing seems to work and I am stumped.

谢谢

推荐答案

你可以结合使用 $objectToArray$arrayToObject 通过动态字段名称过滤您的对象,但如果您在构建查询时知道您的参数,那么使用常规 .find() 并应用投影:

You could use a combination of $objectToArray and $arrayToObject to filter your object by dynamic field names but if your parameters are known when you're building your query then it's easier to use regular .find() and apply projection:

db.collection.find({},{ "rank.Person1": 1,  "rank.Person2": 1})

let input = ['Person1', 'Person2'];
let entries = input.map(p => ([`rank.${p}`, 1]))
let projection = Object.fromEntries(entries);
console.log(projection);

蒙戈游乐场

这篇关于如何在 mongoose 中使用一组值查询一组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆