简体   繁体   English

如何从 MongoDB 的数组中找到并显示特定的 object?

[英]How do I find and display a specific object from an array in MongoDB?

In my app, I am having trouble writing a mongo script to find and display the service logs to one vehicle.在我的应用程序中,我无法编写一个 mongo 脚本来查找和显示服务日志到一辆车。 For example, I have two users with multiple vehicles.例如,我有两个拥有多辆车的用户。 Each vehicle has multiple service logs.每辆车都有多个服务日志。 With the queries I wrote, I'm not having much luck displaying only the serviceLogs objects from the second user with _id:"2" from the vehicle with _id:14 .通过我编写的查询,我没有太多运气仅显示来自具有_id:"2"的第二个用户的serviceLogs对象来自具有_id:14vehicle Below is the sample data.下面是样本数据。

db.collection.insert(
{_id:"1",vehicles:[
{_id:11,make:"Mazda",model:"CX5",serviceLogs:[
{_id:110, "miles" : 7567,"service" : "Wipers replacement"}
]}]});

db.collection.insert(
{_id:"2",vehicles:[
{_id:12,make:"Mazda",model:"CX5",serviceLogs:[]},
{_id:13,make:"Chevy",model:"Sonic",serviceLogs:[]},
{_id:14,make:"Toyota",model:"Tacoma",serviceLogs:[
{_id:111, "miles" : 2134,"service" : "Brake pads replacement"},
{_id:112, "miles" : 5678,"service" : "VSS replacement"}
]}]});

Below are the queries I tried, I've tinkered around with them but not getting any luck.以下是我尝试过的查询,我对它们进行了修改,但没有得到任何运气。

db.collection.find({"_id": "2", vehicles: {$elemMatch: {make: "Toyota", model: "Tacoma"}}} ).pretty();
db.collection.find({"_id": "2", "vehicles.$.serviceLogs": {$elemMatch: {serviceLogs:{id: 111}}}})
db.collection.find({"_id": "2", vehicles: {$elemMatch: {serviceLogs:{id: 111}}}})

Expected results:预期成绩:

{
  "_id" : 111.0,
  "miles" : 2134.0,
  "service" : "Brake pads replacement"
}, 
{
  "_id" : 112.0,
  "miles" : 5678.0,
  "service" : "VSS replacement"
}

Any suggestions would be greatly appreciated, thanks.任何建议将不胜感激,谢谢。

Try this:尝试这个:

db.collection.find({"_id": "2", vehicles: {$elemMatch: {make: "Toyota", model: "Tacoma"}}} ).project({serviceLogs: 1});

More info here: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/更多信息在这里: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

Although I did not get the exact answer I initially expected, I have a query that also got the vehicle information along with the service logs.虽然我没有得到我最初期望的确切答案,但我有一个查询,其中还获得了车辆信息以及服务日志。 This is better as I am able to retrieve the vehicle make, model, and all of its service logs.这更好,因为我能够检索车辆制造商 model 及其所有服务日志。 This query will return only one vehicle that meets the _id and vehicle._id .此查询将仅返回一辆满足_idvehicle._id的车辆。 Below is an example query for the vehicle with _id:"2" .下面是带有_id:"2"的车辆的示例查询。

db.collection.aggregate([
    { $match: { _id: "2" } },
    {
      $project: {
        vehicles: {
          $filter: {
            input: "$vehicles",
            as: "vehicle",
            cond: { $eq: ["$$vehicle._id", 14] }
          }
        },
        _id: 0
      }
    }
  ]).pretty()

This query will yield the result below:此查询将产生以下结果:

{
    "vehicles" : [
            {
                    "_id" : 14,
                    "make" : "Toyota",
                    "model" : "Tacoma",
                    "serviceLogs" : [
                            {
                                    "_id" : 111,
                                    "miles" : 2134,
                                    "service" : "Brake pads replacement"
                            },
                            {
                                    "_id" : 112,
                                    "miles" : 5678,
                                    "service" : "VSS replacement"
                            }
                    ]
            }
    ]
}

Using MongoDB's aggregate and $project , I am able to retrieve just the data from the vehicle I am targeting.使用 MongoDB 的聚合$project ,我可以只从目标车辆中检索数据。 In my React application, below is the sample code I used to assign the vehicle data to React states.在我的 React 应用程序中,下面是我用来将车辆数据分配给 React 状态的示例代码。

API.getOneVehicleForUser(this.state.uid, this.state.vehicleId) // API call passing in the user ID and the vehicle id we want to target
  .then(res => { // After the API call returns successfully, we assign the data to React states
      this.setState({
        make: res.data[0].vehicles[0].make,
        model: res.data[0].vehicles[0].model,
        serviceLogs: res.data[0].vehicles[0].serviceLogs
      })
  .catch(err => console.log(err)); // Do anything you want here to handle errors if the API call should fail

this.state.serviceLogs is an array, which stores all of the vehicle service logs. this.state.serviceLogs是一个数组,存储了所有的车辆服务日志。 Here I can do anything I want, such as count and display how many service logs the vehicle has using this.state.serviceLogs.length or display each service log by their miles and service type.在这里,我可以做任何我想做的事情,例如使用this.state.serviceLogs.length计算和显示车辆有多少服务日志,或者按里程服务类型显示每个服务日志。

I know this may not be the cleanest solution, but for my application, it has been working very well.我知道这可能不是最干净的解决方案,但对于我的应用程序来说,它运行得非常好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用MongoDB,如何使用变量中的对象更新数组中的对象? - With MongoDB, how do I update an object within in array with an object from a variable? 我想将JSON对象中的特定内容显示为表结构吗? 我怎样才能做到这一点? - I want to display specific contents from JSON object into a table structure? how can i do that? 如何根据对对象的了解,从数组中查找和删除对象? - How do I find and remove an object from an array based on what I know about the contents of that object? 如何使用ng-repeat显示数组中对象的特定属性 - How can I display a specific property from an object in an array using ng-repeat 如何在 Angular 中轻松显示来自 MongoDB 的代码数组? - How can I easily display an array of codes from MongoDB in Angular? 如何在MongoDB中的数组中列出对象的字段? - How do I list fields in object inside array in MongoDB? ReactJs:如何通过单击从对象数组中显示 object 的特定数据 - ReactJs : How to display a specific data of an object from an array of objects with a click 如何使用 React Native 从 mongoDB 显示/渲染图像? - How do I display/render image from mongoDB with react native? 如何通过将值与另一个数组匹配,从数组中正确找到 object 中的值 - How do I correctly find a value in an object from an array, by matching it to another array with the values 如何设置数组中特定对象的属性? mongodb - How to set an property of a specific object in an array? mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM