1

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?

1
  • can you add your expected result. Commented Sep 27, 2020 at 10:20

2 Answers 2

1

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

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

Comments

1

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")})

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.