Question about query....!


 db.trips.findOne({"_id" : ObjectId("572bb8222b288919b68abf6d")},{"start station location.coordinates" : 1})
{
        "_id" : ObjectId("572bb8222b288919b68abf6d"),
        "start station location" : {
                "coordinates" : [
                        -73.960876,
                        40.710451
                ]
        }
}

i want to query only -73.960876.

so i change query, but it didnt work.

db.trips.findOne({"_id" : ObjectId("572bb8222b288919b68abf6d")},{"start station location.coordinates.$" : 1})
Error: error: {
        "operationTime" : Timestamp(1642127887, 1),
        "ok" : 0,
        "errmsg" : "positional operator '.$' couldn't find a matching element in the array",
        "code" : 51246,
        "codeName" : "Location51246",
        "$clusterTime" : {
                "clusterTime" : Timestamp(1642127887, 1),
                "signature" : {
                        "hash" : BinData(0,"9q0C1ZIZ38rnl53i2Gi14UfrZAw="),
                        "keyId" : NumberLong("7048178359372611588")
                }
        }
} 

can you help me??

Hi @Sungwon_Yoon ,

I don’t see how a coordinate can consist of only one value .

Why would you need that?

Thanks
Pavel

If you want to query on a specific element of an array you may use the dot notation with the element index.

c.find( {"start station location.coordinates.0" : -73.960876 })

However, while your post title and test mention query, the usage you shared looks like you mean projection.
To project specific array element you need to use $slice.

db.trips.findOne({"_id" : ObjectId("572bb8222b288919b68abf6d")},{_id:1,"start station location.coordinates" : { "$slice" : [ 0 , 1 ] } })

I don’t think that @Sungwon_Yoon, wants coordinates with a single value. But querying one of the value may occurs like in M001, Chapter 4: Advanced CRUD Operations - Lab 1: Querying Arrays and Sub-Documents:

How many trips in the sample_training.trips collection started at stations that are to the west of the -74 longitude coordinate?

Longitude decreases in value as you move west.

Note: We always list the longitude first and then latitude in the coordinate pairs; i.e.

<field_name>: [ <longitude>, <latitude> ]

By the example posted, it looks like he is working on this lab but used a projection rather than a query.

3 Likes

Thank you. it works!! very helpful. Thanks!.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.