2

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

2
  • Why not use an array for ranks instead of nested objects? Commented Jul 7, 2020 at 9:26
  • @ParthShah That would be the better option... Commented Jul 7, 2020 at 9:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.