简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM