colla
colla

Reputation: 837

Mongoose (MongodDB) find ObjectId in array of ObjectId

I am using nodejs, mongoose (so mongodb as a database) and javascript.

I have a collection named A which some examples are the following:

{
   "item": "Kitchen",
   "location": "New York",
   "ids" : [ ObjectId("5f6dce24021e15a1121a649a"), ObjectId("5f6dce24021e15a1121a649b"), ObjectId("5f6dce24021e15a112a649c")]
}
{
   "item": "Bathroom",
   "location": "New York",
   "ids" : [ObjectId("5f6dce24021e15a112a649c")]
}
{
   "item": "Living Room",
   "location": "New York",
   "ids" : [ ObjectId("5f6dce24021e15a1121a649a"), ObjectId("5f6dce24021e15a1121a649b")]
}

The ids are the references to another collection which I will name B. An example would in the collection B is the following:

{
  "_id" : ObjectId("5f6dce24021e15a1121a649a"),
  "name" : "George",
  "Age": 12,
  "Nationality": "English"
}

I would like to be able to find all items in collection A which have ObjectId("5f6dce24021e15a1121a649a") in the ids array.

Excepted Result: ["Kitchen", "Living Room"]

Does anyone have an idea how I could processed?

Upvotes: 1

Views: 71

Answers (2)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

Mongo allows you to query arrays the same way you query a none-array field.

It also has a built in distinct function to fetch unique values from a query.

db.collection.distinct("item", {ids: ObjectId("5f6dce24021e15a1121a649a")})

Upvotes: 1

turivishal
turivishal

Reputation: 36114

You can use aggregate() method,

  • $match search id in ids array
  • $group all item in items array
db.A.aggregate([
  { $match: { ids: ObjectId("5f6dce24021e15a1121a649a") } },
  {
    $group: {
      _id: null,
      items: { $push: "$item" }
    }
  }
])

Playground


You can use find() method,

let result = await db.A.find(
  { ids: ObjectId("5f6dce24021e15a1121a649a") },
  { _id: 0, item: 1 }
);
let items = result.map(obj => obj.item);
console.log(items);

Playground

Upvotes: 1

Related Questions