How do I query a set of objects with an array of values in mongoose?

耗尽温柔 提交于 2021-01-28 03:41:41

问题


I have a schema like this

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 }

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

Thanks


回答1:


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);

Mongo Playground



来源:https://stackoverflow.com/questions/62772021/how-do-i-query-a-set-of-objects-with-an-array-of-values-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!