Javascript 如何按数组中的特定对象值进行搜索,并仅返回mongoDB中搜索的对象

Javascript 如何按数组中的特定对象值进行搜索,并仅返回mongoDB中搜索的对象,javascript,node.js,mongodb,vue.js,Javascript,Node.js,Mongodb,Vue.js,我试图查询嵌套在数组中的对象值,并仅返回该值(连同嵌套在其中的整个对象) 我尝试了以下代码,但它返回了affiliate数组中的所有附属公司,而我只想要我搜索的一个: // data structure : { _id: 1, name: vendorName, countryCode: US, affiliates: [{ number: 1, name: affName }, { number: 2, name

我试图查询嵌套在数组中的对象值,并仅返回该值(连同嵌套在其中的整个对象)

我尝试了以下代码,但它返回了affiliate数组中的所有附属公司,而我只想要我搜索的一个:

// data structure : 
{
  _id: 1,
  name: vendorName,
  countryCode: US,
  affiliates: [{
      number: 1,
      name: affName
    },
    {
      number: 2,
      name: affName
    }
  ]

async function getDetails(user){

    let vendorQuery = {
        countryCode: user.countryCode,
        affiliates: {
          $elemMatch: {
            number: user.affiliateNumber
          }
        }
    }
    let db = await mongoService.connect()
    const collection = db.collection('vendors');
    let vendorDetails = await collection.find( vendorQuery, {'affiliates.$':1} ).toArray()
    console.log('brokerDetails : ',brokerDetails);

    return vendorDetails
}


因此,在上面的代码中,我希望返回vendor对象,但只返回匹配的附属机构,而不是所有附属机构

您需要使用$projection操作符从数组中仅返回匹配的值

另外,
affiliatesQuery
需要将stop作为
countryQuery
的一部分,并且整个stop应该是
find
查询的第一个参数

find
查询的第二个参数应该是
projection

试试这个:

let countryQuery = {
    countryCode: user.countryCode,
    affiliates.number: user.affiliateNumber
  }

  let db = await mongoService.connect()
  const collection = db.collection('vendors');
  let vendorDetails = await collection.find(countryQuery, {'affiliates.$':1}).toArray()


您可以使用聚合管道

const db = await mongoService.connect();
const collection = db.collection('vendors');
const result = await collection.aggregate([
  // query documents
  {
    $match: {
      countryCode: user.countryCode,
      'affiliates.number': user.affiliateNumber,
    }
  },
  // unwind affiliates array
  {
    $unwind : '$affiliates',
  },
  // filter docs again
  {
    $match: {
      'affiliates.number': user.affiliateNumber,
    },
  },
  // you can even replace root of the doc and return just object you need
  {
    $replaceRoot: { newRoot: "$affiliates" }
  }
])

return result

感谢answar,但是我仍然在附属机构数组中得到2对象。您可以显示您的查询,您尝试了什么,因为$只返回一个元素(数组中第一个匹配的元素)是的,我已经根据新的元素编辑了代码,请看一看,它应该是collection.find(vendorQuery).project({'associates.$':1})。toArray(),谢谢您的帮助同样,我所建议的也是投影语法,我不知道为什么它对您不起作用。您需要按照使用
.project()
方法语法。比如-
let vendorDetails=wait collection.find(vendorQuery).project({'affiliates.$':1}).toArray()
谢谢,它成功了!我不明白为什么文档中的syntex不同。无论如何谢谢你