Reputation: 341
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?
Upvotes: 1
Views: 1342
Reputation: 22276
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'
]
Upvotes: 2
Reputation: 27
You can use following query to convert object to string
> db.objectidToStringDemo.aggregate([{$project: {toUser: {$toString: "$toUser"}}}]);
Upvotes: 0
Reputation: 50291
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)
Upvotes: 1