1

valueOf() returns this:

[
   {},
   { toUser: '5ed9d49c7e516616600eb693' },       
   { toUser: '5ed9d49c7e516616600eb693' },       
   { toUser: '5ed9d49c7e516616600eb693' },       
   { toUser: '5ed9d3897e516616600eb692' }        
]

I want to return only the value like "5ed9d3897e516616600eb692" or whatever toUser has. How?

2
  • could you show us the full code? Commented Jun 8, 2020 at 11:12
  • do you need array of id strings instead of array of object? Commented Jun 8, 2020 at 11:15

3 Answers 3

2

This can be done in a couple of different ways, the best of which is using distinct:

db.collection.distinct("toUser")

Output will be:

[
    '5ed9d49c7e516616600eb693',
    '5ed9d49c7e516616600eb693',
    '5ed9d49c7e516616600eb693',
    '5ed9d3897e516616600eb692'
]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use reduce and inside callback check if the object has any key using Object.keys and length. If it has k then push the value using Object.values into the accumulator array

let data = [{},
  {
    toUser: '5ed9d49c7e516616600eb693'
  },
  {
    toUser: '5ed9d49c7e516616600eb693'
  },
  {
    toUser: '5ed9d49c7e516616600eb693'
  },
  {
    toUser: '5ed9d3897e516616600eb692'
  }
];
let filterdValue = data.reduce((acc, curr) => {
  const objKey = Object.keys(curr);
  if (objKey.length > 0) {
    acc.push(...Object.values(curr))
  }
  return acc;
}, []);
console.log(filterdValue)

Comments

0

You can use following query to convert object to string

> db.objectidToStringDemo.aggregate([{$project: {toUser: {$toString: "$toUser"}}}]);

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.